1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://h2database.com/html/license.html). |
4 | * Initial Developer: H2 Group |
5 | */ |
6 | package org.h2.command.dml; |
7 | |
8 | import java.io.BufferedReader; |
9 | import java.io.IOException; |
10 | import java.io.InputStreamReader; |
11 | import java.nio.charset.Charset; |
12 | import org.h2.command.CommandInterface; |
13 | import org.h2.command.Prepared; |
14 | import org.h2.engine.Constants; |
15 | import org.h2.engine.Session; |
16 | import org.h2.message.DbException; |
17 | import org.h2.result.ResultInterface; |
18 | import org.h2.util.ScriptReader; |
19 | |
20 | /** |
21 | * This class represents the statement |
22 | * RUNSCRIPT |
23 | */ |
24 | public class RunScriptCommand extends ScriptBase { |
25 | |
26 | /** |
27 | * The byte order mark. |
28 | * 0xfeff because this is the Unicode char |
29 | * represented by the UTF-8 byte order mark (EF BB BF). |
30 | */ |
31 | private static final char UTF8_BOM = '\uFEFF'; |
32 | |
33 | private Charset charset = Constants.UTF8; |
34 | |
35 | public RunScriptCommand(Session session) { |
36 | super(session); |
37 | } |
38 | |
39 | @Override |
40 | public int update() { |
41 | session.getUser().checkAdmin(); |
42 | int count = 0; |
43 | try { |
44 | openInput(); |
45 | BufferedReader reader = new BufferedReader(new InputStreamReader(in, charset)); |
46 | // if necessary, strip the BOM from the front of the file |
47 | reader.mark(1); |
48 | if (reader.read() != UTF8_BOM) { |
49 | reader.reset(); |
50 | } |
51 | ScriptReader r = new ScriptReader(reader); |
52 | while (true) { |
53 | String sql = r.readStatement(); |
54 | if (sql == null) { |
55 | break; |
56 | } |
57 | execute(sql); |
58 | count++; |
59 | if ((count & 127) == 0) { |
60 | checkCanceled(); |
61 | } |
62 | } |
63 | reader.close(); |
64 | } catch (IOException e) { |
65 | throw DbException.convertIOException(e, null); |
66 | } finally { |
67 | closeIO(); |
68 | } |
69 | return count; |
70 | } |
71 | |
72 | private void execute(String sql) { |
73 | try { |
74 | Prepared command = session.prepare(sql); |
75 | if (command.isQuery()) { |
76 | command.query(0); |
77 | } else { |
78 | command.update(); |
79 | } |
80 | if (session.getAutoCommit()) { |
81 | session.commit(false); |
82 | } |
83 | } catch (DbException e) { |
84 | throw e.addSQL(sql); |
85 | } |
86 | } |
87 | |
88 | public void setCharset(Charset charset) { |
89 | this.charset = charset; |
90 | } |
91 | |
92 | @Override |
93 | public ResultInterface queryMeta() { |
94 | return null; |
95 | } |
96 | |
97 | @Override |
98 | public int getType() { |
99 | return CommandInterface.RUNSCRIPT; |
100 | } |
101 | |
102 | } |