Exemple #1
0
  private void visit(Procedure procedure) {
    if (this.filter != null && !filter.matcher(procedure.getName()).matches()) {
      return;
    }

    append(CREATE).append(SPACE);
    if (procedure.isVirtual()) {
      append(VIRTUAL);
    } else {
      append(FOREIGN);
    }
    append(SPACE)
        .append(procedure.isFunction() ? FUNCTION : PROCEDURE)
        .append(SPACE)
        .append(SQLStringVisitor.escapeSinglePart(procedure.getName()));
    append(LPAREN);

    boolean first = true;
    for (ProcedureParameter pp : procedure.getParameters()) {
      if (first) {
        first = false;
      } else {
        append(COMMA).append(SPACE);
      }
      visit(pp);
    }
    append(RPAREN);

    if (procedure.getResultSet() != null) {
      append(SPACE).append(RETURNS);
      appendOptions(procedure.getResultSet());
      append(SPACE).append(TABLE).append(SPACE);
      addColumns(procedure.getResultSet().getColumns(), true);
    }
    /* The parser treats the RETURN clause as optional for a procedure if using the RESULT param
      for (ProcedureParameter pp: procedure.getParameters()) {
    	if (pp.getType().equals(Type.ReturnValue)) {
    		append(SPACE).append(RETURNS).append(SPACE);
    		appendColumn(buffer, pp, false, true);
    		break;
    	}
    }*/

    // options
    String options = buildProcedureOptions(procedure);
    if (!options.isEmpty()) {
      append(NEWLINE).append(OPTIONS).append(SPACE).append(LPAREN).append(options).append(RPAREN);
    }
    // block
    if (procedure.isVirtual()) {
      append(NEWLINE).append(SQLConstants.Reserved.AS).append(NEWLINE);
      String plan = procedure.getQueryPlan();
      append(plan);
    }

    append(SEMICOLON);
  }
Exemple #2
0
 protected ProcParameter getProcParameter(Database catalog_db, Procedure catalog_proc, int idx) {
   assertNotNull(catalog_db);
   assert (idx >= 0) : "Invalid ProcParameter index for " + catalog_proc + ": " + idx;
   assert (idx < catalog_proc.getParameters().size())
       : "Invalid ProcParameter index for " + catalog_proc + ": " + idx;
   ProcParameter catalog_param = catalog_proc.getParameters().get(idx);
   assertNotNull("Null ProcParameter index for " + catalog_proc + ": " + idx, catalog_param);
   return (catalog_param);
 }
Exemple #3
0
  public static String addProcedure() {
    Procedure A = new Procedure(Procedure.getProcedure(), Procedure.getCost());
    p_procList.add(A);
    String newProcedure = null;
    for (int i = 0; i < p_procList.size(); i++) {

      newProcedure = newProcedure + Procedure.getProcedure() + Procedure.getCost();
    }
    return newProcedure;
  }
  /**
   * Some prepared statements return multiple results; the execute method handles these complex
   * statements as well as the simpler form of statements handled by executeQuery and executeUpdate.
   *
   * @exception SQLException if a database-access error occurs.
   * @see Statement#execute
   */
  public boolean execute(Tds tds) throws SQLException {
    //
    // TDS can handle prepared statements by creating a temporary
    // procedure.  Since procedure must have the datatype specified
    // in the procedure declaration we will have to defer creating
    // the actual procedure until the statement is executed.  By
    // that time we know all the types of all of the parameters.
    //

    Procedure procedure = null;
    boolean result = false;

    // SAfe No need for this either. We'll have to consume all input, nut
    //      just the last ResultSet (if one exists).
    //        closeResults(false);
    // SAfe No need for this. getMoreResults sets it to -1 at start, anyway
    //        updateCount = -2;

    // First make sure the caller has filled in all the parameters.
    ParameterUtils.verifyThatParametersAreSet(parameterList);

    // Find a stored procedure that is compatible with this set of parameters if one exists.
    procedure = findCompatibleStoredProcedure(tds, rawQueryString);
    // now look in tds

    // if we don't have a suitable match then create a new temporary stored procedure
    if (procedure == null) {
      // Create the stored procedure
      procedure = new Procedure(rawQueryString, tds.getUniqueProcedureName(), parameterList, tds);

      // SAfe Submit it to the SQL Server before adding it to the cache or procedures of transaction
      // list.
      //      Otherwise, if submitProcedure fails (e.g. because of a syntax error) it will be in our
      // procedure
      //      cache, but not on the server.
      submitProcedure(tds, procedure);

      // store it in the procedureCache
      tds.procedureCache.put(rawQueryString, procedure);

      // MJH Only record the proc name in proceduresOfTra if in manual commit mode
      if (!getConnection().getAutoCommit()) // MJH
      tds.proceduresOfTra.add(procedure);
    }

    result =
        internalExecuteCall(
            procedure.getProcedureName(),
            procedure.getParameterList(),
            parameterList,
            tds,
            warningChain);

    return result;
  }
Exemple #5
0
 @SuppressWarnings("unchecked")
 public void transformProcedure(Procedure proc) {
   List<ReturnStatement> ret_stmts =
       (new DFIterator<ReturnStatement>(proc, ReturnStatement.class)).getList();
   CompoundStatement body = proc.getBody();
   List ret_type = proc.getReturnType();
   // Remove scope qualifiers not necessary in type resolution
   while (ret_type.remove(Specifier.INLINE)) ;
   while (ret_type.remove(Specifier.STATIC)) ;
   while (ret_type.remove(Specifier.EXTERN)) ;
   boolean ret_type_void = (ret_type.contains(Specifier.VOID) && ret_type.size() == 1);
   Identifier ret_id = null;
   // add a variable _ret_val of the same type as the procedure return type
   if (!ret_type_void) {
     // check for implicit int (TODO - differentiate this from constructors)
     if (ret_type.isEmpty()) {
       ret_type.add(Specifier.INT);
     }
     ret_id = SymbolTools.getTemp(body, ret_type, "_ret_val");
   }
   // add a labeled return statement to the end of the procedure
   String done_label = "_done";
   body.addStatement(new Label(new NameID(done_label)));
   if (!ret_type_void) {
     body.addStatement(new ReturnStatement(ret_id.clone()));
   } else {
     body.addStatement(new ReturnStatement());
   }
   // redirect the preexisting return statements to the labeled return
   for (ReturnStatement ret_stmt : ret_stmts) {
     // Identify the parent compound statement.
     CompoundStatement comp_stmt = IRTools.getAncestorOfType(ret_stmt, CompoundStatement.class);
     // Add goto statement.
     Statement goto_stmt = new GotoStatement(new NameID(done_label));
     comp_stmt.addStatementAfter(ret_stmt, goto_stmt);
     // Add temporary assignments.
     if (!ret_type_void) {
       Statement new_stmt =
           new ExpressionStatement(
               new AssignmentExpression(
                   ret_id.clone(), AssignmentOperator.NORMAL, ret_stmt.getExpression().clone()));
       comp_stmt.addStatementBefore(goto_stmt, new_stmt);
     }
     // Remove the original return statement.
     comp_stmt.removeStatement(ret_stmt);
     // Add comments.
     /*
     CommentAnnotation info =
             new CommentAnnotation("Normalized Return: " + ret_stmt);
     info.setOneLiner(true);
     goto_stmt.annotateBefore(info);
     */
   }
 }
Exemple #6
0
 protected Statement getStatement(Database catalog_db, Procedure catalog_proc, String stmt_name) {
   assertNotNull(catalog_db);
   assertNotNull(catalog_proc);
   Statement catalog_stmt = catalog_proc.getStatements().get(stmt_name);
   assert (catalog_stmt != null)
       : "Failed to retrieve Statement '"
           + stmt_name
           + "' from Procedure '"
           + catalog_proc.getName()
           + "'";
   return (catalog_stmt);
 }
Exemple #7
0
  public static final File fileHandle(Value o) {
    String encoding = "UTF-8"; // always supported

    try {
      URL u = url(o);
      if (!"file".equals(u.getProtocol()))
        Procedure.throwPrimException(liMessage(IO.IOB, "notafileurl"));
      String path = URLDecoder.decode(u.getPath(), encoding);
      return new File(path);
    } catch (UnsupportedEncodingException use) {
      Procedure.throwPrimException(liMessage(IO.IOB, "unsupencoding", encoding));
      return null; // not reached
    }
  }
  /**
   * Some prepared statements return multiple results; the execute method handles these complex
   * statements as well as the simpler form of statements handled by executeQuery and executeUpdate.
   *
   * @exception SQLException if a database-access error occurs.
   * @see Statement#execute
   */
  public boolean execute(Tds tds) throws SQLException {
    //
    // TDS can handle prepared statements by creating a temporary
    // procedure.  Since procedure must have the datatype specified
    // in the procedure declaration we will have to defer creating
    // the actual procedure until the statement is executed.  By
    // that time we know all the types of all of the parameters.
    //

    Procedure procedure = null;
    boolean result = false;

    closeResults();
    updateCount = -2;

    // First make sure the caller has filled in all the parameters.
    ParameterUtils.verifyThatParametersAreSet(parameterList);

    // Find a stored procedure that is compatible with this set of
    // parameters if one exists.
    procedure = findCompatibleStoredProcedure(tds, rawQueryString);
    // now look in tds

    // if we don't have a suitable match then create a new
    // temporary stored procedure
    if (procedure == null) {
      // create the stored procedure
      procedure = new Procedure(rawQueryString, tds.getUniqueProcedureName(), parameterList, tds);

      // store it in the procedureCache
      // procedureCache.addElement(procedure);
      // store it in the procedureCache
      tds.procedureCache.put(rawQueryString, procedure);
      tds.proceduresOfTra.add(procedure);

      // create it on the SQLServer.
      submitProcedure(tds, procedure);
    }
    result =
        executeCall(
            tds,
            procedure.getProcedureName(),
            procedure.getParameterList(),
            // formal params
            parameterList);
    // actual params

    return result;
  }
Exemple #9
0
 public WrongType(Procedure proc, int n, Object argValue, Type expectedType) {
   this.proc = proc;
   this.procname = proc.getName();
   this.number = n;
   this.argValue = argValue;
   this.expectedType = expectedType;
 }
Exemple #10
0
 public int effectiveIndex(int[] indexes) {
   Object obj;
   try {
     obj = proc.apply1(indexes);
   } catch (Throwable ex) {
     throw new RuntimeException("index transformer throw " + ex, ex);
   }
   if (obj instanceof int[]) return base.effectiveIndex((int[]) obj);
   IntSequence ind = Sequences.asIntSequenceOrNull(obj);
   if (ind == null) throw new ClassCastException("not an integer sequence");
   if (ind instanceof S32Vector) return base.effectiveIndex(((S32Vector) ind).getBuffer());
   else {
     int rank = ind.size();
     switch (rank) {
       case 0:
         return base.effectiveIndex();
       case 1:
         return base.effectiveIndex(ind.getInt(0));
       case 2:
         return base.effectiveIndex(ind.getInt(0), ind.getInt(1));
       default:
         int[] rest = rank == 3 ? AbstractSequence.noInts : new int[rank - 3];
         for (int i = 3; i < rank; i++) rest[i - 3] = ind.getInt(i);
         return base.effectiveIndex(ind.getInt(0), ind.getInt(1), ind.getInt(2), rest);
     }
   }
 }
Exemple #11
0
 public E get(int[] indexes) {
   try {
     return (E) proc.apply1(new S32Vector(indexes));
   } catch (Throwable ex) {
     throw new RuntimeException("caught " + ex + " evaluating array procedure", ex);
   }
 }
Exemple #12
0
  private String buildProcedureOptions(Procedure procedure) {
    StringBuilder options = new StringBuilder();
    addCommonOptions(options, procedure);

    if (procedure.getUpdateCount() != Procedure.AUTO_UPDATECOUNT) {
      addOption(options, UPDATECOUNT, procedure.getUpdateCount());
    }

    if (!procedure.getProperties().isEmpty()) {
      for (String key : procedure.getProperties().keySet()) {
        addOption(options, key, procedure.getProperty(key, false));
      }
    }

    return options.toString();
  }
 protected T coerce(T newValue) {
   try {
     return (T) converter.apply1(newValue);
   } catch (Throwable ex) {
     throw WrappedException.rethrow(ex);
   }
 }
Exemple #14
0
  @Override
  protected void makeConnectors() {
    super.makeConnectors();

    // Variable
    variableCon = new Connector();
    variableCon.detouch();
    variableCon.setWidth(50);
    variableCon.setHeight(2);
    variableCon.setHolder(this);
    variableCon.setPosition(Connector.Position.LEFT);
    AnchorPane.setTopAnchor(variableCon, 10.0);
    AnchorPane.setLeftAnchor(variableCon, 10.0);
    variableCon.toFront();

    leftVariableCon = new Connector();
    leftVariableCon.detouch();
    leftVariableCon.setWidth(50);
    leftVariableCon.setHeight(2);
    leftVariableCon.setHolder(this);
    leftVariableCon.setPosition(Connector.Position.INSIDE_LEFT);
    AnchorPane.setTopAnchor(leftVariableCon, 10.0);
    AnchorPane.setLeftAnchor(leftVariableCon, 80.0);
    leftVariableCon.toFront();

    getChildren().addAll(variableCon, leftVariableCon);
  }
 public void lineStart(boolean flag) throws IOException {
   if (flag) {
     break MISSING_BLOCK_LABEL_64;
   }
   if (tie != null) {
     tie.freshLine();
   }
   if (prompter == null) {
     break MISSING_BLOCK_LABEL_64;
   }
   Object obj;
   try {
     obj = prompter.apply1(this);
   } catch (Throwable throwable) {
     throw new IOException(
         (new StringBuilder())
             .append("Error when evaluating prompt:")
             .append(throwable)
             .toString());
   }
   if (obj == null) {
     break MISSING_BLOCK_LABEL_64;
   }
   obj = obj.toString();
   if (obj == null) {
     break MISSING_BLOCK_LABEL_64;
   }
   if (((String) (obj)).length() > 0) {
     emitPrompt(((String) (obj)));
     promptEmitted = true;
   }
 }
Exemple #16
0
 public void apply(CallContext ctx) throws Throwable {
   Object proc = func.eval(ctx);
   int n = args.length;
   Object[] vals = new Object[n];
   for (int i = 0; i < n; i++) vals[i] = args[i].eval(ctx);
   ((Procedure) proc).checkN(vals, ctx);
 }
 public static void withServerIdImmutability(Procedure fn) {
   try {
     SystemEnvironment.enforceServerIdImmutability.set(true);
     fn.call();
   } finally {
     SystemEnvironment.enforceServerIdImmutability.set(false);
   }
 }
Exemple #18
0
  @Test
  public void testTypeLength() throws Exception {
    String ddl =
        "CREATE FOREIGN PROCEDURE myProc(OUT p1 boolean, p2 varchar, INOUT p3 decimal) "
            + "RETURNS (r1 varchar(10), r2 decimal(11,2), r3 object(1), r4 clob(10000))"
            + "OPTIONS(RANDOM 'any', UUID 'uuid', NAMEINSOURCE 'nis', ANNOTATION 'desc', UPDATECOUNT '2');";

    Schema s = helpParse(ddl, "model").getSchema();
    Procedure proc = s.getProcedure("myProc");
    assertNotNull(proc);

    List<Column> cols = proc.getResultSet().getColumns();
    assertEquals(10, cols.get(0).getLength());
    assertEquals(11, cols.get(1).getPrecision());
    assertEquals(1, cols.get(2).getLength());
    assertEquals(10000, cols.get(3).getLength());
  }
Exemple #19
0
  @Test
  public void testMultipleCommands() throws Exception {
    String ddl =
        "CREATE VIEW V1 AS SELECT * FROM PM1.G1 "
            + "CREATE PROCEDURE FOO(P1 integer) RETURNS (e1 integer, e2 varchar) AS SELECT * FROM PM1.G1;";

    Schema s = helpParse(ddl, "model").getSchema();
    Map<String, Table> tableMap = s.getTables();
    Table table = tableMap.get("V1");
    assertNotNull(table);
    assertEquals("SELECT * FROM PM1.G1", table.getSelectTransformation());

    Map<String, Procedure> procedureMap = s.getProcedures();
    Procedure p = procedureMap.get("FOO");
    assertNotNull(p);
    assertEquals("SELECT * FROM PM1.G1;", p.getQueryPlan());
  }
Exemple #20
0
  @Test
  public void testAlterProcedureOptions() throws Exception {
    String ddl =
        "CREATE FOREIGN PROCEDURE myProc(OUT p1 boolean, p2 varchar, INOUT p3 decimal) "
            + "RETURNS (r1 varchar, r2 decimal)"
            + "OPTIONS(RANDOM 'any', UUID 'uuid', NAMEINSOURCE 'nis', ANNOTATION 'desc', UPDATECOUNT '2');"
            + "ALTER FOREIGN PROCEDURE myProc OPTIONS(SET NAMEINSOURCE 'x')"
            + "ALTER FOREIGN PROCEDURE myProc ALTER PARAMETER p2 OPTIONS (ADD x 'y');"
            + "ALTER FOREIGN PROCEDURE myProc OPTIONS(DROP UPDATECOUNT);";

    Schema s = helpParse(ddl, "model").getSchema();
    Procedure proc = s.getProcedure("myProc");
    assertNotNull(proc);

    assertEquals("x", proc.getNameInSource());
    assertEquals("p2", proc.getParameters().get(1).getName());
    assertEquals("y", proc.getParameters().get(1).getProperty("x", false));
    assertEquals(1, proc.getUpdateCount());
  }
Exemple #21
0
 @Override
 public void toFront() {
   super.toFront();
   if (variable != null) {
     variable.toFront();
   }
   if (leftVariable != null) {
     leftVariable.toFront();
   }
 }
  /**
   * passes parameters to relevant setters of a Procedure object to update
   *
   * @param myProcedure
   * @param procName
   * @param procCostString
   * @return boolean representing success of operation
   */
  public boolean updateProcedure(Procedure myProcedure, String procName, String procCostString) {
    if (procName.isEmpty() && procCostString.isEmpty()) // display error if no details entered
    {
      JOptionPane.showMessageDialog(null, "No details entered");
      return false;
    }
    // if any detail is provided, update accordingly
    if (!procName.isEmpty()) myProcedure.setProcedureName(procName);
    if (!procCostString.isEmpty()) {
      try {
        Double tempProcCost = Double.parseDouble(procCostString);
        myProcedure.setCost(tempProcCost);
      } catch (NumberFormatException n) {
        JOptionPane.showMessageDialog(null, "Please ensure a valid price is entered.");
        return false;
      }
    }

    JOptionPane.showMessageDialog(null, "Procedure details updated");
    return true;
  }
Exemple #23
0
 @Override
 public void move(double dx, double dy) {
   if (variable != null) {
     variable.toFront();
     variable.move(dx + 10, dy + 10);
   }
   if (leftVariable != null) {
     leftVariable.toFront();
     leftVariable.move(dx + 80, dy + 10);
   }
   super.move(dx, dy);
 }
Exemple #24
0
  @Override
  public void show() {
    super.show();

    if (variable != null) {
      variable.show();
    }

    if (leftVariable != null) {
      leftVariable.show();
    }
  }
Exemple #25
0
 private static int effectiveIndex(Array array, Procedure proc, Object[] args, int[] work)
     throws Throwable {
   Object mapval = proc.applyN(args);
   if (mapval instanceof Values) {
     Values mapvals = (Values) mapval;
     for (int i = 0, j = 0; (i = mapvals.nextPos(i)) != 0; j++) {
       work[j] = ((Number) mapvals.getPosPrevious(i)).intValue();
     }
   } else work[0] = ((Number) mapval).intValue();
   if (array instanceof GeneralArray) return ((GeneralArray) array).resolve(work);
   else return work[0];
 }
Exemple #26
0
 @Override
 public String getCreateStatement() {
   return ""
       + "CREATE TRIGGER "
       + this.name
       + " "
       + "AFTER INSERT OR UPDATE OR DELETE ON "
       + table
       + " "
       + "FOR EACH ROW EXECUTE PROCEDURE "
       + procedure.getName()
       + "();"
       + "";
 }
Exemple #27
0
 @Override
 public void create(boolean ignoreAlreadyExists) throws SQLException {
   super.create(ignoreAlreadyExists);
   PreparedStatement ps =
       yordifier
           .getConnection()
           .prepareStatement(
               "INSERT INTO "
                   + Yordifier.TRIGGERS
                   + " (NAME, FUNCTION_NAME, TABLE_NAME) VALUES (?, ?, ?)");
   ps.setString(1, name);
   ps.setString(2, procedure.getName());
   ps.setString(3, table);
   ps.execute();
 }
Exemple #28
0
 public FcudaStreamData(
     Procedure kernel,
     ForLoop streamLoop,
     IDExpression streamLoopVar,
     IDExpression streamLoopBound,
     IDExpression streamLoopUpdate) {
   loops = new LinkedList<ForLoop>();
   loops.add(streamLoop);
   // loopVar = streamLoopVar;
   loopVars = new LinkedList<IDExpression>();
   loopVars.add(streamLoopVar);
   loopBounds = new LinkedList<IDExpression>();
   loopBounds.add(streamLoopBound);
   // loopUpdate = streamLoopUpdate;
   loopUpdates = new LinkedList<IDExpression>();
   loopUpdates.add(streamLoopUpdate);
   kernelName = kernel.getName();
   mConstMemIDs = new HashSet<IDExpression>();
   mConstMemIDs.clear();
 }
  /**
   * removes a procedure from the system collections
   *
   * @param myProcedure
   * @return boolean, represents success or failure
   */
  public boolean deleteProcedure(Procedure myProcedure) {
    for (int i = 0; i < procedureList.size(); i++) {
      if (procedureList.get(i).getMyProcNo() == myProcedure.getMyProcNo()) {
        int result =
            JOptionPane.showConfirmDialog(
                null,
                "Are you sure you wish to permanently delete this procedure record?",
                null,
                JOptionPane.YES_NO_OPTION);
        if (result == JOptionPane.YES_OPTION) {
          procedureList.remove(i);
          JOptionPane.showMessageDialog(null, "Procedure removed");
          return true;
        } else return false;
      }
    }

    JOptionPane.showMessageDialog(null, "Procedure not found");
    return false;
  }
Exemple #30
0
 /**
  * Inline this ApplyExp if parameters are constant.
  *
  * @param proc the procedure bound to this.func.
  * @return the constant result (as a QuoteExp) if inlining was possible; otherwise this ApplyExp.
  *     If applying proc throws an exception, print a warning on walker.messages.
  */
 public final Expression inlineIfConstant(Procedure proc, SourceMessages messages) {
   int len = args.length;
   Object[] vals = new Object[len];
   for (int i = len; --i >= 0; ) {
     Expression arg = args[i];
     if (arg instanceof ReferenceExp) {
       Declaration decl = ((ReferenceExp) arg).getBinding();
       if (decl != null) {
         arg = decl.getValue();
         if (arg == QuoteExp.undefined_exp) return this;
       }
     }
     if (!(arg instanceof QuoteExp)) return this;
     vals[i] = ((QuoteExp) arg).getValue();
   }
   try {
     return new QuoteExp(proc.applyN(vals), type);
   } catch (Throwable ex) {
     if (messages != null) messages.error('w', "call to " + proc + " throws " + ex);
     return this;
   }
 }