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.ddl; |
7 | |
8 | import org.h2.api.ErrorCode; |
9 | import org.h2.command.CommandInterface; |
10 | import org.h2.engine.Database; |
11 | import org.h2.engine.Session; |
12 | import org.h2.expression.Expression; |
13 | import org.h2.message.DbException; |
14 | import org.h2.schema.Constant; |
15 | import org.h2.schema.Schema; |
16 | import org.h2.value.Value; |
17 | |
18 | /** |
19 | * This class represents the statement |
20 | * CREATE CONSTANT |
21 | */ |
22 | public class CreateConstant extends SchemaCommand { |
23 | |
24 | private String constantName; |
25 | private Expression expression; |
26 | private boolean ifNotExists; |
27 | |
28 | public CreateConstant(Session session, Schema schema) { |
29 | super(session, schema); |
30 | } |
31 | |
32 | public void setIfNotExists(boolean ifNotExists) { |
33 | this.ifNotExists = ifNotExists; |
34 | } |
35 | |
36 | @Override |
37 | public int update() { |
38 | session.commit(true); |
39 | session.getUser().checkAdmin(); |
40 | Database db = session.getDatabase(); |
41 | if (getSchema().findConstant(constantName) != null) { |
42 | if (ifNotExists) { |
43 | return 0; |
44 | } |
45 | throw DbException.get(ErrorCode.CONSTANT_ALREADY_EXISTS_1, constantName); |
46 | } |
47 | int id = getObjectId(); |
48 | Constant constant = new Constant(getSchema(), id, constantName); |
49 | expression = expression.optimize(session); |
50 | Value value = expression.getValue(session); |
51 | constant.setValue(value); |
52 | db.addSchemaObject(session, constant); |
53 | return 0; |
54 | } |
55 | |
56 | public void setConstantName(String constantName) { |
57 | this.constantName = constantName; |
58 | } |
59 | |
60 | public void setExpression(Expression expr) { |
61 | this.expression = expr; |
62 | } |
63 | |
64 | @Override |
65 | public int getType() { |
66 | return CommandInterface.CREATE_CONSTANT; |
67 | } |
68 | |
69 | } |