Debian Codegraph @

src/test/org/h2/samples/DirectInsert.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.samples;
7
8 import java.sql.Connection;
9 import java.sql.DriverManager;
10 import java.sql.PreparedStatement;
11 import java.sql.SQLException;
12 import java.sql.Statement;
13 import java.util.concurrent.TimeUnit;
14
15 import org.h2.tools.DeleteDbFiles;
16
17 /**
18 * Demonstrates the benefit of using the CREATE TABLE ... AS SELECT
19 * optimization.
20 */
21 public class DirectInsert {
22
23 /**
24 * This method is called when executing this sample application from the
25 * command line.
26 *
27 * @param args the command line parameters
28 * @throws Exception on failure
29 */
30 public static void main(String... args) throws Exception {
31 Class.forName("org.h2.Driver");
32 DeleteDbFiles.execute("~", "test", true);
33 String url = "jdbc:h2:~/test";
34 initialInsert(url, 200_000);
35 for (int i = 0; i < 3; i++) {
36 createAsSelect(url, true);
37 createAsSelect(url, false);
38 }
39 }
40
41 private static void initialInsert(String url, int len) throws SQLException {
42 Connection conn = DriverManager.getConnection(url + ";LOG=0");
43 Statement stat = conn.createStatement();
44 stat.execute("DROP TABLE IF EXISTS TEST");
45 stat.execute("CREATE TABLE TEST(ID INT PRIMARY KEY, NAME VARCHAR)");
46 PreparedStatement prep = conn.prepareStatement(
47 "INSERT INTO TEST VALUES(?, 'Test' || SPACE(100))");
48 long time = System.nanoTime();
49 for (int i = 0; i < len; i++) {
50 long now = System.nanoTime();
51 if (now > time + TimeUnit.SECONDS.toNanos(1)) {
52 time = now;
53 System.out.println("Inserting " + (100L * i / len) + "%");
54 }
55 prep.setInt(1, i);
56 prep.execute();
57 }
58 conn.commit();
59 prep.close();
60 stat.close();
61 conn.close();
62 }
63
64 private static void createAsSelect(String url, boolean optimize)
65 throws SQLException {
66 Connection conn = DriverManager.getConnection(url +
67 ";OPTIMIZE_INSERT_FROM_SELECT=" + optimize);
68 Statement stat = conn.createStatement();
69 stat.execute("DROP TABLE IF EXISTS TEST2");
70 System.out.println("CREATE TABLE ... AS SELECT " +
71 (optimize ? "(optimized)" : ""));
72 long time = System.nanoTime();
73 stat.execute("CREATE TABLE TEST2 AS SELECT * FROM TEST");
74 System.out.printf("%.3f sec.\n", (double) (System.nanoTime() - time) /
75 TimeUnit.SECONDS.toNanos(1));
76 stat.execute("INSERT INTO TEST2 SELECT * FROM TEST2");
77 stat.close();
78 conn.close();
79 }
80
81 }