| 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.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.SessionLocal; |
| 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 SchemaOwnerCommand { |
| 23 |
|
| 24 |
private String constantName; |
| 25 |
private Expression expression; |
| 26 |
private boolean ifNotExists; |
| 27 |
|
| 28 |
public CreateConstant(SessionLocal session, Schema schema) { |
| 29 |
super(session, schema); |
| 30 |
} |
| 31 |
|
| 32 |
public void setIfNotExists(boolean ifNotExists) { |
| 33 |
this.ifNotExists = ifNotExists; |
| 34 |
} |
| 35 |
|
| 36 |
@Override |
| 37 |
long update(Schema schema) { |
| 38 |
Database db = getDatabase(); |
| 39 |
if (schema.findConstant(constantName) != null) { |
| 40 |
if (ifNotExists) { |
| 41 |
return 0; |
| 42 |
} |
| 43 |
throw DbException.get(ErrorCode.CONSTANT_ALREADY_EXISTS_1, constantName); |
| 44 |
} |
| 45 |
int id = getObjectId(); |
| 46 |
Constant constant = new Constant(schema, id, constantName); |
| 47 |
expression = expression.optimize(session); |
| 48 |
Value value = expression.getValue(session); |
| 49 |
constant.setValue(value); |
| 50 |
db.addSchemaObject(session, constant); |
| 51 |
return 0; |
| 52 |
} |
| 53 |
|
| 54 |
public void setConstantName(String constantName) { |
| 55 |
this.constantName = constantName; |
| 56 |
} |
| 57 |
|
| 58 |
public void setExpression(Expression expr) { |
| 59 |
this.expression = expr; |
| 60 |
} |
| 61 |
|
| 62 |
@Override |
| 63 |
public int getType() { |
| 64 |
return CommandInterface.CREATE_CONSTANT; |
| 65 |
} |
| 66 |
|
| 67 |
} |