Beispiel #1
0
  public void doCommand(final String input) {
    // Split command name from arguments.
    final String[] commandSplit = input.split(" ", 2);

    final String command = commandSplit[0];
    final String tail = (commandSplit.length == 2) ? commandSplit[1] : null;

    // Dispatch command.
    final Command primitiveCommand = primitive.get(command);

    if (primitiveCommand != null) {
      // Invoke primitive command.
      if (tail != null) {
        primitiveCommand.execute(this, tail);
      } else {
        primitiveCommand.execute(this);
      }
    } else {
      // Schedule non-primitive call.
      if (tail != null) {
        scriptRunner.call(command, tail.split(" "));
      } else {
        scriptRunner.call(command);
      }
    }
  }
  @Test
  public void scriptRunnerShouldBatchMySQLFunctionsAndProcedures() throws Exception {
    ScriptRunner runner = new ScriptRunner(DatabaseType.MYSQL);
    Reader reader =
        new InputStreamReader(getClass().getResourceAsStream("stored-procedure-mysql.sql"));
    MockConnection connection = new MockConnection();

    runner.execute(connection, reader);

    List statements = connection.getStatementResultSetHandler().getExecutedStatements();

    assertThat(statements.size(), is(3));
    assertThat(
        statements.get(0).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE FUNCTION hello (s CHAR(20)) RETURNS CHAR(50) DETERMINISTIC RETURN CONCAT('Hello, ',s,'!')")));
    assertThat(
        statements.get(1).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE FUNCTION weighted_average (n1 INT, n2 INT, n3 INT, n4 INT) RETURNS INT DETERMINISTIC BEGIN DECLARE avg INT; SET avg = (n1+n2+n3*2+n4*4)/8; RETURN avg; END")));
    assertThat(
        statements.get(2).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE PROCEDURE payment(payment_amount DECIMAL(6,2), payment_seller_id INT) BEGIN DECLARE n DECIMAL(6,2); SET n = payment_amount - 1.00; INSERT INTO Moneys VALUES (n, CURRENT_DATE); IF payment_amount > 1.00 THEN UPDATE Sellers SET commission = commission + 1.00 WHERE seller_id = payment_seller_id; END IF; END")));
  }
 @Test
 public void testConsole() throws Exception {
   HashMap<String, Object> ctx = new HashMap<String, Object>();
   ScriptRunner runner = new ScriptRunner(".", ctx);
   runner.require("src/main/javascript/util/io.js");
   runner.require("src/main/javascript/util/io-unit-test.js");
 }
  @Test
  public void scriptRunnerShouldBatchPostgresFunctionsAndProcedures() throws Exception {
    ScriptRunner runner = new ScriptRunner(DatabaseType.POSTGRESQL);
    Reader reader =
        new InputStreamReader(getClass().getResourceAsStream("stored-procedure-postgresql.sql"));
    MockConnection connection = new MockConnection();

    runner.execute(connection, reader);

    List statements = connection.getStatementResultSetHandler().getExecutedStatements();

    assertThat(statements.size(), is(4));
    assertThat(
        statements.get(0).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE FUNCTION getQtyOrders(customerID int) RETURNS int AS $$ DECLARE qty int; BEGIN SELECT COUNT(*) INTO qty FROM Orders WHERE accnum = customerID; RETURN qty; END; $$ LANGUAGE plpgsql")));
    assertThat(
        statements.get(1).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE FUNCTION one() RETURNS integer AS ' SELECT 1 AS result; ' LANGUAGE SQL")));
    assertThat(
        statements.get(2).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE FUNCTION emp_stamp() RETURNS trigger AS $emp_stamp$ BEGIN IF NEW.empname IS NULL THEN RAISE EXCEPTION 'empname cannot be null'; END IF; IF NEW.salary IS NULL THEN RAISE EXCEPTION '% cannot have null salary', NEW.empname; END IF; IF NEW.salary < 0 THEN RAISE EXCEPTION '% cannot have a negative salary', NEW.empname; END IF; NEW.last_date := current_timestamp; NEW.last_user := current_user; RETURN NEW; END; $emp_stamp$ LANGUAGE plpgsql")));
    assertThat(statements.get(3).toString(), is(equalToIgnoringWhiteSpace("SELECT one()")));
  }
 @Override
 protected void createTables() throws Exception {
   // Execute SQL to setup the database for the test
   ScriptRunner scriptRunner = new ScriptRunner(cdb.getDatabase("dbid-1"), false);
   scriptRunner.setResourceName("/scripts/oracle-createtables.sql");
   scriptRunner.executeScript();
 }
 @Test
 public void testScriptRunner() throws Exception {
   HashMap<String, Object> ctx = new HashMap<String, Object>();
   ctx.put("hello", "Hello");
   ScriptRunner runner = new ScriptRunner(".", ctx);
   runner.require("src/main/javascript/util/io.js");
   runner.eval("print('ctx hello = ' +  hello + '\\n')");
   runner.eval("print('ctx hello = ' +  JSON.stringify({name: 'Tuan'}))");
 }
 @Test
 public void shouldRunScriptsUsingConnection() throws Exception {
   DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
   Connection conn = ds.getConnection();
   ScriptRunner runner = new ScriptRunner(conn);
   runner.setAutoCommit(true);
   runner.setStopOnError(false);
   runner.setErrorLogWriter(null);
   runner.setLogWriter(null);
   runJPetStoreScripts(runner);
   assertProductsTableExistsAndLoaded();
 }
 @Test
 public void shouldRunScriptsUsingProperties() throws Exception {
   Properties props = Resources.getResourceAsProperties(JPETSTORE_PROPERTIES);
   DataSource dataSource =
       new UnpooledDataSource(
           props.getProperty("driver"),
           props.getProperty("url"),
           props.getProperty("username"),
           props.getProperty("password"));
   ScriptRunner runner = new ScriptRunner(dataSource.getConnection());
   runner.setAutoCommit(true);
   runner.setStopOnError(false);
   runner.setErrorLogWriter(null);
   runner.setLogWriter(null);
   runJPetStoreScripts(runner);
   assertProductsTableExistsAndLoaded();
 }
  @Test
  public void scriptRunnerShouldHandleComplexCommands() throws Exception {
    ScriptRunner runner = new ScriptRunner(DatabaseType.MYSQL);
    Reader reader = new InputStreamReader(getClass().getResourceAsStream("complex.sql"));
    MockConnection connection = new MockConnection();

    runner.execute(connection, reader);

    List statements = connection.getStatementResultSetHandler().getExecutedStatements();

    String expectedSql =
        "update dav_file set parent = ( select id from ( select id from dav_file where name = '__SITE_PROTECTED__' ) as x )"
            + " where ( name = 'templates' and parent is null )"
            + " or ( name = 'velocity' and parent is null )"
            + " or ( name = 'tags' and parent is null )"
            + " or ( name = 'ctd' and parent is null )";

    assertThat(statements.size(), is(1));
    assertThat(statements.get(0).toString(), is(equalToIgnoringWhiteSpace(expectedSql)));
  }
  @Test
  public void scriptRunnerShouldBatchSimpleCommands() throws Exception {
    ScriptRunner runner = new ScriptRunner(DatabaseType.UNKNOWN);
    Reader reader = new InputStreamReader(getClass().getResourceAsStream("simple.sql"));
    MockConnection connection = new MockConnection();

    runner.execute(connection, reader);

    List statements = connection.getStatementResultSetHandler().getExecutedStatements();

    assertThat(statements.size(), is(2));
    assertThat(
        statements.get(0).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "create table users ( username varchar not null, password varchar not null )")));
    assertThat(
        statements.get(1).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "alter table users add index (username), add unique (username)")));
  }
  @Test
  public void scriptRunnerShouldUseTheSameDelimiterUntilExplicitlyChanged() throws Exception {
    ScriptRunner runner = new ScriptRunner(DatabaseType.UNKNOWN);
    Reader reader = new InputStreamReader(getClass().getResourceAsStream("function-mysql.sql"));
    MockConnection connection = new MockConnection();

    runner.execute(connection, reader);

    List statements = connection.getStatementResultSetHandler().getExecutedStatements();

    assertThat(statements.size(), is(3));
    assertThat(
        statements.get(0).toString(),
        is(equalToIgnoringWhiteSpace("DROP FUNCTION IF EXISTS simpleFunction")));
    assertThat(
        statements.get(1).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "CREATE FUNCTION simpleFunction() RETURNS varchar(100) READS SQL DATA begin declare message varchar(100) default 'Hello Word'; return message; end")));
    assertThat(
        statements.get(2).toString(), is(equalToIgnoringWhiteSpace("select simpleFunction()")));
  }
  @Test
  public void scriptRunnerShouldExecuteLastStatementWhenDelimiterIsMissing() throws Exception {
    ScriptRunner runner = new ScriptRunner(DatabaseType.UNKNOWN);
    Reader reader =
        new InputStreamReader(getClass().getResourceAsStream("missing-last-deliminator.sql"));
    MockConnection connection = new MockConnection();

    runner.execute(connection, reader);

    List statements = connection.getStatementResultSetHandler().getExecutedStatements();

    assertThat(statements.size(), is(2));
    assertThat(
        statements.get(0).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "create table users ( username varchar not null, password varchar not null )")));
    assertThat(
        statements.get(1).toString(),
        is(
            equalToIgnoringWhiteSpace(
                "create table roles ( name varchar not null unique, description text not null )")));
  }
  public synchronized void start(int nThreads) {
    if (executor != null) {
      return;
    }
    scriptRunner = new ScriptRunner(this);
    scriptRunner.init();
    executor = Executors.newScheduledThreadPool(nThreads);
    for (int i = 0; i < nThreads; i++) {
      long initDelay = (long) (1000L * options.delay * i / nThreads);
      long delay = (long) (1000L * options.delay);
      if (initDelay <= 0) initDelay = 0;
      if (delay <= 0) delay = 1;
      executor.scheduleWithFixedDelay(scriptRunner, initDelay, delay, TimeUnit.MILLISECONDS);
    }

    printExecutor = Executors.newSingleThreadScheduledExecutor();
    printExecutor.scheduleWithFixedDelay(new StatsPrinter(), 500L, 1000L, TimeUnit.MILLISECONDS);
  }
Beispiel #14
0
 @Test
 @Ignore("This fails with HSQLDB 2.0 due to the create index statements in the schema script")
 public void shouldRunScriptsBySendingFullScriptAtOnce() throws Exception {
   DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
   Connection conn = ds.getConnection();
   ScriptRunner runner = new ScriptRunner(conn);
   runner.setSendFullScript(true);
   runner.setAutoCommit(true);
   runner.setStopOnError(false);
   runner.setErrorLogWriter(null);
   runner.setLogWriter(null);
   runJPetStoreScripts(runner);
   assertProductsTableExistsAndLoaded();
 }
Beispiel #15
0
  @Test
  public void shouldReturnWarningIfEndOfLineTerminatorNotFound() throws Exception {
    DataSource ds = createUnpooledDataSource(JPETSTORE_PROPERTIES);
    Connection conn = ds.getConnection();
    ScriptRunner runner = new ScriptRunner(conn);
    runner.setAutoCommit(true);
    runner.setStopOnError(false);
    runner.setErrorLogWriter(null);
    runner.setLogWriter(null);

    String resource = "org/apache/ibatis/jdbc/ScriptMissingEOLTerminator.sql";
    Reader reader = Resources.getResourceAsReader(resource);

    try {
      runner.runScript(reader);
      fail("Expected script runner to fail due to missing end of line terminator.");
    } catch (Exception e) {
      assertTrue(e.getMessage().contains("end-of-line terminator"));
    }
  }
Beispiel #16
0
 @Override
 public String getDescription(AIHelper helper) {
   return scriptRunner.getDescription(helper);
 }
 public void run() {
   ScriptRunner runner = getScriptRunner();
   if (runner != null) {
     runner.getStats().report(options.slowQueriesToShow);
   }
 }
    public void apply(final Object target) {
      DefaultServiceRegistry services = new DefaultServiceRegistry();
      services.add(ScriptPluginFactory.class, DefaultScriptPluginFactory.this);
      services.add(ScriptHandlerFactory.class, scriptHandlerFactory);
      services.add(ClassLoaderScope.class, targetScope);
      services.add(LoggingManagerInternal.class, loggingManagerFactory.create());
      services.add(Instantiator.class, instantiator);
      services.add(ScriptHandler.class, scriptHandler);
      services.add(FileLookup.class, fileLookup);
      services.add(ModelRuleSourceDetector.class, modelRuleSourceDetector);

      ScriptSource withImports = importsReader.withImports(scriptSource);

      PluginDependenciesService pluginDependenciesService =
          new PluginDependenciesService(getSource());
      services.add(PluginDependenciesService.class, pluginDependenciesService);

      ScriptCompiler compiler = scriptCompilerFactory.createCompiler(withImports);
      compiler.setClassloader(baseScope.getExportClassLoader());

      boolean supportsPluginsBlock = ProjectScript.class.isAssignableFrom(scriptType);
      String onPluginBlockError =
          supportsPluginsBlock ? null : "Only Project build scripts can contain plugins {} blocks";

      PluginsAndBuildscriptTransformer scriptBlockTransformer =
          new PluginsAndBuildscriptTransformer(
              classpathClosureName, onPluginBlockError, documentationRegistry);

      StatementExtractingScriptTransformer classpathScriptTransformer =
          new StatementExtractingScriptTransformer(classpathClosureName, scriptBlockTransformer);

      compiler.setTransformer(classpathScriptTransformer);

      ScriptRunner<? extends BasicScript> classPathScriptRunner = compiler.compile(scriptType);
      classPathScriptRunner.getScript().init(target, services);
      classPathScriptRunner.run();

      List<PluginRequest> pluginRequests = pluginDependenciesService.getRequests();
      PluginAwareInternal pluginAware =
          target instanceof PluginAwareInternal ? (PluginAwareInternal) target : null;
      pluginRequestApplicator.applyPlugins(pluginRequests, scriptHandler, pluginAware, targetScope);

      compiler.setClassloader(targetScope.getLocalClassLoader());

      BuildScriptTransformer transformer =
          new BuildScriptTransformer(
              "no_" + classpathScriptTransformer.getId(),
              classpathScriptTransformer.invert(),
              scriptSource);
      compiler.setTransformer(transformer);

      // TODO - find a less tangled way of getting this in here, see the verifier impl for why it's
      // needed
      compiler.setVerifier(new ClosureCreationInterceptingVerifier());

      ScriptRunner<? extends BasicScript> runner = compiler.compile(scriptType);

      BasicScript script = runner.getScript();
      script.init(target, services);
      if (ownerScript && target instanceof ScriptAware) {
        ((ScriptAware) target).setScript(script);
      }
      runner.run();
    }
Beispiel #19
0
 @Override
 protected void onDeactivate(AIHelper helper) {
   scriptRunner.stop();
   super.onDeactivate(helper);
 }
Beispiel #20
0
 @Override
 public boolean checkShouldTakeOver(AIHelper helper) {
   return !scriptRunner.isFinished();
 }
Beispiel #21
0
 @Override
 protected TickResult onGameTick(AIHelper helper) {
   return scriptRunner.runForTick(helper);
 }
 public static void createDatabaseStructure(Reader ddl, Connection connection)
     throws ClassNotFoundException, SQLException, FileNotFoundException, IOException {
   ScriptRunner runner = new ScriptRunner(connection, true, true);
   runner.runScript(ddl);
 }