Package org.voltdb.catalog

Examples of org.voltdb.catalog.Procedure


        }
        for (Entry<Statement, Statement> e : this.optimized.entrySet()) {
            // Make a back-up for each original Statement
            Statement backup = this.backups.get(e.getKey());
            if (backup == null) {
                Procedure catalog_proc = e.getKey().getParent();
                backup = catalog_proc.getStatements().add("BACKUP__" + e.getKey().getName());
                if (debug.val)
                    LOG.debug(String.format("Created temporary catalog object %s to back-up %s's query plans", backup.getName(), e.getKey().fullName()));
                this.backups.put(e.getKey(), backup);
                boolean ret = catalog_proc.getStatements().remove(backup);
                assert (ret);
                assert (catalog_proc.getStatements().contains(backup) == false);
            }
            VerticalPartitionPlanner.applyOptimization(e.getKey(), backup);

            // Then copy the optimized query plans
            if (debug.val)
View Full Code Here


                    LOG.warn(String.format("Failed to generate optimized queries for %s\n%s", vc.getClass().getSimpleName(), vc));
                } else {
                    assert (vc.hasOptimizedQueries()) : vc;
                    Statement catalog_stmt = CollectionUtil.first(vc.getOptimizedQueries());
                    assert (catalog_stmt != null);
                    Procedure catalog_proc = catalog_stmt.getParent();
                    String stmtName = catalog_stmt.getName();
                    if (vc.isUpdateApplied() == false)
                        vc.applyUpdate();

                    catalog_stmt = catalog_proc.getStatements().get(stmtName);
                    AbstractPlanNode root = PlanNodeUtil.getRootPlanNodeForStatement(catalog_stmt, false);
                    if (debug)
                        LOG.debug(catalog_stmt.fullName() + "\n" + PlanNodeUtil.debug(root));
                    clearCache = true;
                }
            } // FOR
            if (clearCache) {
                CatalogUtil.clearCache(catalog_db);
                PlanNodeUtil.clearCache();
            }
        }

        for (Procedure catalog_proc : catalog_db.getProcedures()) {
            ProcedureEntry pentry = this.proc_entries.get(catalog_proc);
            if (catalog_proc.getSystemproc() || pentry == null || catalog_proc.getParameters().size() == 0)
                continue;
            if (debug)
                LOG.debug("Applying PartitionEntry to " + catalog_proc.getName() + ": " + pentry);

            ProcParameter catalog_proc_param = null;
            switch (pentry.getMethod()) {
                case NONE:
                    catalog_proc_param = NullProcParameter.singleton(catalog_proc);
                    break;
                case RANDOM:
                    catalog_proc_param = RandomProcParameter.singleton(catalog_proc);
                    break;
                case HASH:
                    catalog_proc_param = pentry.getAttribute();
                    break;
                default:
                    assert (false) : "Unexpected PartitionMethodType for " + catalog_proc + ": " + pentry.getMethod();
            } // SWITCH

            assert (catalog_proc_param != null) : "Null ProcParameter for " + catalog_proc;
            catalog_proc.setPartitionparameter(catalog_proc_param.getIndex());

            Boolean single_partition = pentry.isSinglePartition();
            if (single_partition != null)
                catalog_proc.setSinglepartition(single_partition);
        } // FOR
    }
View Full Code Here

                    throw ex;
                }

                // Procedure Partitioning
            } else if (e.getKey() instanceof Procedure) {
                Procedure catalog_proc = (Procedure) e.getKey();
                ProcParameter catalog_proc_param = (ProcParameter) e.getValue();
                boolean single_partition = true;
                ProcParameter attribute = null;

                if (catalog_proc.getSystemproc()) {
                    continue;
                } else if (catalog_proc_param instanceof NullProcParameter || catalog_proc_param == null || catalog_proc.getParameters().size() == 0) {
                    method = PartitionMethodType.NONE;
                    single_partition = false;
                    // attribute =
                    // NullProcParameter.getNullProcParameter(catalog_proc);
                } else {
                    method = PartitionMethodType.HASH;
                    attribute = catalog_proc_param;
                    single_partition = catalog_proc.getSinglepartition();
                    assert (catalog_proc_param != null) : "Unexcept Null ProcParameter: " + catalog_proc;
                    assert (catalog_proc_param.getParent().equals(e.getKey())) : "Parent mismatch: " + catalog_proc_param.getParent() + " != " + e.getKey();
                }
                ProcedureEntry pentry = new ProcedureEntry(method, attribute, single_partition);
                try {
View Full Code Here

     * @param query
     * @return
     * @throws Exception
     */
    private ClientResponse execProcedure(Client client, String procName, String query, boolean reconnect) throws Exception {
        Procedure catalog_proc = this.catalog_db.getProcedures().getIgnoreCase(procName);
        if (catalog_proc == null) {
            throw new Exception("Invalid stored procedure name '" + procName + "'");
        }
       
        // We now need to go through the rest of the parameters and convert them
        // to proper type
        Pattern p = Pattern.compile("^" + Command.EXEC.name() + "[ ]+" + procName + "[ ]+(.*?)[;]*", Pattern.CASE_INSENSITIVE);
        Matcher m = p.matcher(query);
        List<Object> procParams = new ArrayList<Object>();
        if (m.matches()) {
            // Extract the parameters and then convert them to their appropriate type
            List<String> params = HStoreTerminal.extractParams(m.group(1));
            if (debug.val) LOG.debug("PARAMS: " + params);
            if (params.size() != catalog_proc.getParameters().size()) {
                String msg = String.format("Expected %d params for '%s' but %d parameters were given",
                                           catalog_proc.getParameters().size(), catalog_proc.getName(), params.size());
                throw new Exception(msg);
            }
            int i = 0;
            for (ProcParameter catalog_param : catalog_proc.getParameters()) {
                VoltType vtype = VoltType.get(catalog_param.getType());
                Object value = VoltTypeUtil.getObjectFromString(vtype, params.get(i));
               
                // HACK: Allow us to send one-element array parameters
                if (catalog_param.getIsarray()) {
                    switch (vtype) {
                        case BOOLEAN:
                            value = new boolean[]{ (Boolean)value };
                            break;
                        case TINYINT:
                        case SMALLINT:
                        case INTEGER:
                            value = new int[]{ (Integer)value };
                            break;
                        case BIGINT:
                            value = new long[]{ (Long)value };
                            break;
                        case FLOAT:
                        case DECIMAL:
                            value = new double[]{ (Double)value };
                            break;
                        case STRING:
                            value = new String[]{ (String)value };
                            break;
                        case TIMESTAMP:
                            value = new TimestampType[]{ (TimestampType)value };
                        default:
                            assert(false);
                    } // SWITCH
                }
                procParams.add(value);
                i++;
            } // FOR
        }
       
        Object params[] = procParams.toArray();
        if (this.enable_csv == false && reconnect == false) {
            LOG.info(String.format("Executing transaction " + setBoldText + "%s(%s)" + setPlainText,
                     catalog_proc.getName(), StringUtil.toString(params, false, false)));
        }
        ClientResponse cresponse = client.callProcedure(catalog_proc.getName(), params);
        return (cresponse);
    }
View Full Code Here

                    // ----------------------------------------------
                    // PROCEDURE PARTITIONING PARAMETER
                    // ----------------------------------------------
                } else {
                    Procedure current_proc = (Procedure) current;
                    ProcParameter current_proc_param = (ProcParameter) attribute;
                    assert (current_proc_param != null);
                    current_proc.setPartitionparameter(current_proc_param.getIndex());
                    memory = parent.memory;
                    current_attribute = current_proc_param;
                }

                // ----------------------------------------------
                // COST ESTIMATION
                // ----------------------------------------------
                Double cost = null;
                Double singlep_txns = null;
                // Don't estimate the cost if it doesn't fit
                if (!memory_exceeded) {
                    cost = this.cost_model.estimateWorkloadCost(info.catalogContext, info.workload, filter, best_vertex.cost);
                    singlep_txns = this.cost_model.getSinglePartitionProcedureHistogram().getSampleCount() / (double) this.cost_model.getProcedureHistogram().getSampleCount();
                } else {
                    cost = Double.MAX_VALUE;
                }

                StateVertex state = new StateVertex(parent, current_key, attribute_key, is_table, cost, singlep_txns, memory);
                if (debug.val)
                    state.debug = cost_model.debugHistograms(info.catalogContext);
                // if (!this.graph.containsVertex(parent))
                // this.graph.addVertex(parent);
                // this.graph.addEdge(new StateEdge(), parent, state,
                // EdgeType.DIRECTED);

                if (local_best_vertex == null || local_best_vertex.cost > state.cost)
                    local_best_vertex = state;
                assert (local_best_vertex != null);

                // ----------------------------------------------
                // DEBUG OUTPUT
                // ----------------------------------------------
                // state.debug = this.cost_model.getLastDebugMessage();
                LOG.info(this.createLevelOutput(state, CatalogUtil.getDisplayName(current_attribute, false), spacer, memory_exceeded));

                // ----------------------------------------------
                // ANALYSIS
                // ----------------------------------------------
                if (memory_exceeded) {
                    if (debug.val)
                        LOG.debug("Memory exceeeded! Skipping solution!");
                    if (vp_col != null) {
                        this.revertVerticalPartitionColumn(vp_col);
                        vp_col = null;
                    }
                    continue;
                }

                // The cost of our parent can never be greater than our cost
                if (!parent.isStartVertex()) {
                    boolean is_valid = MathUtil.greaterThanEquals(cost.floatValue(), parent.cost.floatValue(), 0.001f);

                    if (!is_valid) { // && debug.get()) {
                        Map<String, Object> m0 = new LinkedHashMap<String, Object>();
                        m0.put("Parent State", parent.toString());
                        m0.put("Parent CostModel", parent.debug);
                        m0.put("Parent Catalog", createPartitionPlan(hints, parent, false, false));

                        Map<String, Object> m1 = new LinkedHashMap<String, Object>();
                        m1.put("Current Attribute", current_attribute.fullName());
                        m1.put("Current State", state.toString());
                        m1.put("Current CostModel", cost_model.debugHistograms(info.catalogContext));
                        m1.put("Current Catalog", createPartitionPlan(hints, state, false, false));

                        LOG.error("CURRENT COST IS GREATER THAN CURRENT COST! THIS CANNOT HAPPEN!\n" + StringUtil.formatMaps(m0, m1));

                        cost_model.clear();
                        double cost2 = this.cost_model.estimateWorkloadCost(info.catalogContext, info.workload, filter, best_vertex.cost);
                        LOG.error("Second Time: " + cost2);

                    }
                    assert (is_valid) : attribute_key + ": Parent[" + parent.cost + "] <= Current[" + cost + "]" + "\n" + "Rounded: Parent[" + MathUtil.roundToDecimals(parent.cost, 2)
                            + "] <= Current[" + MathUtil.roundToDecimals(cost, 2) + "]";
                }

                // If this is a complete solution, then check whether if it is
                // the best one that we have seen thus far
                // Allow the current solution to be the best solution if the
                // following criteria are met:
                // (1) It's a complete solution
                // (2) It has not exhausted our per-partition memory limit
                // (4) It is less than the upper bounds limit
                // (3) And one of the following is true:
                // (a) The current best solution is the start vertex
                // (b) Or the current solution has a cost less than the current
                // best solution
                if (complete_solution && memory_exceeded == false && cost < BranchAndBoundPartitioner.this.upper_bounds_vertex.cost
                        && (BranchAndBoundPartitioner.this.best_vertex.isStartVertex() || cost < BranchAndBoundPartitioner.this.best_vertex.cost)) {
                    assert (best_vertex.cost > state.cost) : "Best=" + best_vertex.cost + ", Current=" + state.cost;
                    assert (upper_bounds_vertex.cost > state.cost) : "Upper=" + upper_bounds_vertex.cost + ", Current=" + state.cost;

                    if (debug.val) {
                        LOG.debug("Old Solution:\n" + StringBoxUtil.box(best_vertex.toString()));
                    }
                    BranchAndBoundPartitioner.this.best_vertex = state;
                    if (debug.val) {
                        LOG.debug("New Best Solution:\n" + StringBoxUtil.box(best_vertex.toString()));
                        if (this.cost_model.hasDebugMessages())
                            LOG.debug("Last Cost Model Info:\n " + this.cost_model.getLastDebugMessage());
                    }

                    // Log new solution cost
                    if (hints.shouldLogSolutionCosts())
                        hints.logSolutionCost(state.cost, state.singlep_txns);

                    // Check whether we found our target solution and need to
                    // stop
                    // Note that we only need to compare Tables, because the
                    // Procedure's could have
                    // different parameters for those ones where the parameter
                    // actually doesn't make a difference
                    if (hints.target_plan != null) {
                        if (debug.val)
                            LOG.info("Comparing new best solution with target PartitionPlan");
                        PartitionPlan new_plan = createPartitionPlan(hints, best_vertex, false, false);
                        if (hints.target_plan.getTableEntries().equals(new_plan.getTableEntries())) {
                            this.halt_search = true;
                            this.halt_reason = HaltReason.FOUND_TARGET;
                        }
                    }

                    // for (int i = 0; i <
                    // ((TimeIntervalCostModel)this.cost_model).getIntevalCount();
                    // i++) {
                    // System.err.println("Interval #" + i);
                    // System.err.println(((TimeIntervalCostModel)this.cost_model).getCostModel(i).getTxnPartitionAccessHistogram());
                    // System.err.println("================================================");
                    // }
                    //
                    // System.exit(1);
                }

                // ----------------------------------------------
                // CONTINUE SEARCH TRAVERSAL
                // ----------------------------------------------

                // We now need to look to see whether we should continue down
                // this path. Much like
                // selecting a new best solution, the following criteria must be
                // met in order for
                // the partitioner to be allowed to continue down a search path:
                // (1) If this is last attribute at this level in the tree
                // AND we're looking at a TABLE
                // AND we're doing a greedy search
                // Then we'll always want to keep traversing here.
                // Otherwise, the following the criteria must be met:
                // (1) It must not be a complete solution
                // (2) The current catalog item must be a table (no procedures!)
                // (3) The cost must be less than the current best solution cost
                // (4) The cost must be less than the upper bounds limit
                // Or we can just say screw all that and keep going if the
                // exhaustive flag is enabled
                if (this.halt_search == false
                        && ((last_attribute && is_table && this.hints.greedy_search) || (this.hints.exhaustive_search == true) || (complete_solution == false && is_table
                                && cost < BranchAndBoundPartitioner.this.best_vertex.cost && cost < BranchAndBoundPartitioner.this.upper_bounds_vertex.cost))) {

                    // IMPORTANT: If this is the last table in our traversal,
                    // then we need to switch over
                    // to working Procedures->ProcParameters. We have to now
                    // calculate the list of attributes
                    // that we want to consider
                    // if (is_last_table &&
                    // this.hints.enable_procparameter_search) {
                    // for (int i = idx + 1; i < this.num_elements; i++) {
                    // Procedure catalog_proc =
                    // (Procedure)this.all_search_elements.get(i);
                    // LinkedList<String> attributes =
                    // AbstractPartitioner.generateProcParameterOrder(info,
                    // this.info.catalogContext.database, catalog_proc, hints);
                    //
                    // // We should have ProcParameter candidates!
                    // assert(attributes.isEmpty() == false) :
                    // "No ProcParameter candidates: " + catalog_proc + "\n" +
                    // state;
                    // this.traversal_attributes.get(proc_key).clear();
                    // this.traversal_attributes.get(proc_key).addAll(attributes);
                    // } // FOR
                    // }

                    // We only traverse if this is a table. The ProcParameter
                    // selection is a simple greedy algorithm
                    if (this.hints.greedy_search == false || (this.hints.greedy_search == true && last_attribute)) {
                        if (debug.val && this.hints.greedy_search)
                            LOG.debug(this.createLevelOutput(local_best_vertex, "GREEDY->" + local_best_vertex.getPartitionKey(), spacer, false));
                        this.cp.update(current);
                        this.traverse((this.hints.greedy_search ? local_best_vertex : state), idx + 1);
                        this.cp.reset(current);
                    }
                }
                if (vp_col != null) {
                    this.revertVerticalPartitionColumn(vp_col);
                    vp_col = null;
                }
                if (this.halt_search)
                    break;
            } // FOR

            // ProcParameter Traversal
            if (!is_table && !this.halt_search) {
                assert (local_best_vertex != null) : "Missing local best vertex for " + current_key;

                // Set the partitioning ProcParameter in this Procedure to be
                // the one that
                // had the lowest cost in our search up above.
                Procedure current_proc = (Procedure) current;
                String best_key = local_best_vertex.getPartitionKey();
                ProcParameter current_param = CatalogKey.getFromKey(info.catalogContext.database, best_key, ProcParameter.class);
                assert (current_param != null);
                current_proc.setPartitionparameter(current_param.getIndex());

                // Is this necessary?
                this.cost_model.invalidateCache(current_proc);

                // if (debug.val)
                // LOG.debug(this.createLevelOutput(local_best_vertex,
                // CatalogUtil.getDisplayName(current_param), spacer, false));

                // If there are more Procedures to partition and we have gone
                // past our best cost
                // our upper bounds, then keep going...
                if (complete_solution == false && hints.enable_procparameter_search && (this.hints.greedy_search == true)
                        || (local_best_vertex.cost < best_vertex.cost && local_best_vertex.cost < upper_bounds_vertex.cost)) {
                    this.cp.update(current_proc);
                    this.traverse(local_best_vertex, idx + 1);
                    this.cp.reset(current_proc);
                }

                // Important: We will have to unset the Procedure partitioning
                // parameter
                // if this was the last table and we are going back up the tree.
                // This is because
                // unlike Tables, where we exclude queries using
                // WorkloadFilters, we can't do
                // the same thing for ProcParameters
                // manually once we finish up with this table because the next
                // passes will
                // overwrite the catalog that we saved off
                for (int i = idx; i < this.num_elements; i++) {
                    Procedure catalog_proc = (Procedure) this.all_search_elements.get(i);
                    catalog_proc.setPartitionparameter(-1);
                } // FOR
            }
            if (this.halt_search == false)
                this.backtrack_ctr++;
            return;
View Full Code Here

            catalog_parent = (Cluster) catalog_db.getParent();
            // SPECIAL CASE: StmtParameter
        } else if (catalog_class.equals(StmtParameter.class)) {
            String split[] = PARENT_DELIMITER_REGEX.split(parent_key);
            assert (split.length == 2);
            Procedure catalog_proc = catalog_db.getProcedures().getIgnoreCase(split[0]);
            assert (catalog_proc != null);
            catalog_parent = catalog_proc.getStatements().getIgnoreCase(split[1]);
        }
        // Don't throw this error because it may be a dynamic catalog type that
        // we use for the Markov stuff
        // } else {
        // assert(false) : "Unexpected Catalog key type '" + catalog_class +
View Full Code Here

            // ----------------------------------------------
            // Procedure
            // ----------------------------------------------
        } else if (catalog_obj instanceof Procedure) {
            Procedure catalog_proc = (Procedure) catalog_obj;
            Set<String> proc_attributes = null;
            try {
                proc_attributes = PartitionerUtil.generateProcParameterOrder(this.info, this.catalog_db, catalog_proc, this.hints);
            } catch (Exception ex) {
                throw new RuntimeException(ex);
View Full Code Here

            if (info == null) {
                throw new VoltCompilerException("Sysproc " + shortName + " is missing annotation.");
            }

            // add an entry to the catalog
            final Procedure procedure = database.getProcedures().add(shortName);
            procedure.setId(this.getNextProcedureId());
            procedure.setClassname(procClass.getCanonicalName());
            procedure.setReadonly(readonly);
            procedure.setSystemproc(true);
            procedure.setHasjava(true);
            procedure.setSinglepartition(info.singlePartition());
            procedure.setEverysite(everysite);
            ProcedureCompiler.populateProcedureParameters(this, procClass, procedure);
           
            // ProcInfo.partitionParam overrides everything else
            if (info.partitionParam() != -1) {
                if (info.partitionParam() >= procedure.getParameters().size() || info.partitionParam() < 0) {
                    String msg = "PartitionInfo 'partitionParam' not a valid parameter for procedure: " + procedure.getClassname();
                    throw new VoltCompilerException(msg);
                }
                procedure.setPartitionparameter(info.partitionParam());
            }
            else {
                procedure.setPartitionparameter(NullProcParameter.PARAM_IDX);
            }

            // Stored procedure sysproc classes are present in VoltDB.jar
            // and not duplicated in the catalog. This was decided
            // arbitrarily - no one had a strong opinion.
View Full Code Here

        private final Map<StmtParameter, Map<ProcParameter, ProcParameterCorrelation>> correlations = new ListOrderedMap<StmtParameter, Map<ProcParameter,ProcParameterCorrelation>>();
       
        public QueryInstance(Statement catalog_stmt, Integer index) {
            super(catalog_stmt, index);
           
            Procedure catalog_proc = (Procedure)catalog_stmt.getParent();
            for (StmtParameter catalog_stmt_param : CatalogUtil.getSortedCatalogItems(catalog_stmt.getParameters(), "index")) {
                Map<ProcParameter, ProcParameterCorrelation> c = new ListOrderedMap<ProcParameter, ProcParameterCorrelation>();
                for (ProcParameter catalog_proc_param : CatalogUtil.getSortedCatalogItems(catalog_proc.getParameters(), "index")) {
                    c.put(catalog_proc_param, new ProcParameterCorrelation(catalog_proc_param));
                } // FOR
                this.correlations.put(catalog_stmt_param, c);
            } // FOR
        }
View Full Code Here

    public static void populateCatalog(Database catalog_db, Map<String, DefaultParameterMapping> proc_mapping, boolean force) {
        // For each Procedure in the catalog, we need to find the matching record
        // in the mapping and update the catalog elements as necessary
        for (String proc_name : proc_mapping.keySet()) {
            Procedure catalog_proc = catalog_db.getProcedures().getIgnoreCase(proc_name);
            if (catalog_proc == null) {
                // throw new RuntimeException("Unknown Procedure name '" + proc_name + "' in ParameterMapping");
                continue;
            }
            if (debug.val) LOG.debug("Updating parameter mapping for Procedure '" + proc_name + "'");
           
            DefaultParameterMapping map = proc_mapping.get(proc_name);
            for (String stmt_name : map.keySet()) {
                Statement catalog_stmt = catalog_proc.getStatements().get(stmt_name);
                if (catalog_stmt == null) {
                    throw new RuntimeException("Unknown Statement name '" + stmt_name + "' in ParameterMapping");
                }

                for (Integer stmt_param : map.get(stmt_name).keySet()) {
                    StmtParameter catalog_stmt_param = catalog_stmt.getParameters().get(stmt_param);

                    Integer proc_param = map.get(stmt_name).get(stmt_param);
                    ProcParameter catalog_proc_param = catalog_proc.getParameters().get(proc_param);

                    // Skip if it already has the proper ProcParameter set
                    if (!force && catalog_stmt_param.getProcparameter() != null && catalog_stmt_param.getProcparameter().equals(catalog_proc_param)) {
                        if (debug.val) LOG.debug("Skipping parameter mapping in " + catalog_stmt + " because it is already set");
                    } else {
View Full Code Here

TOP

Related Classes of org.voltdb.catalog.Procedure

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.