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.engine.UserDataType; |
13 | import org.h2.message.DbException; |
14 | import org.h2.table.Column; |
15 | import org.h2.table.Table; |
16 | import org.h2.value.DataType; |
17 | |
18 | /** |
19 | * This class represents the statement |
20 | * CREATE DOMAIN |
21 | */ |
22 | public class CreateUserDataType extends DefineCommand { |
23 | |
24 | private String typeName; |
25 | private Column column; |
26 | private boolean ifNotExists; |
27 | |
28 | public CreateUserDataType(Session session) { |
29 | super(session); |
30 | } |
31 | |
32 | public void setTypeName(String name) { |
33 | this.typeName = name; |
34 | } |
35 | |
36 | public void setColumn(Column column) { |
37 | this.column = column; |
38 | } |
39 | |
40 | public void setIfNotExists(boolean ifNotExists) { |
41 | this.ifNotExists = ifNotExists; |
42 | } |
43 | |
44 | @Override |
45 | public int update() { |
46 | session.getUser().checkAdmin(); |
47 | session.commit(true); |
48 | Database db = session.getDatabase(); |
49 | session.getUser().checkAdmin(); |
50 | if (db.findUserDataType(typeName) != null) { |
51 | if (ifNotExists) { |
52 | return 0; |
53 | } |
54 | throw DbException.get( |
55 | ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1, |
56 | typeName); |
57 | } |
58 | DataType builtIn = DataType.getTypeByName(typeName); |
59 | if (builtIn != null) { |
60 | if (!builtIn.hidden) { |
61 | throw DbException.get( |
62 | ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1, |
63 | typeName); |
64 | } |
65 | Table table = session.getDatabase().getFirstUserTable(); |
66 | if (table != null) { |
67 | throw DbException.get( |
68 | ErrorCode.USER_DATA_TYPE_ALREADY_EXISTS_1, |
69 | typeName + " (" + table.getSQL() + ")"); |
70 | } |
71 | } |
72 | int id = getObjectId(); |
73 | UserDataType type = new UserDataType(db, id, typeName); |
74 | type.setColumn(column); |
75 | db.addDatabaseObject(session, type); |
76 | return 0; |
77 | } |
78 | |
79 | @Override |
80 | public int getType() { |
81 | return CommandInterface.CREATE_DOMAIN; |
82 | } |
83 | |
84 | } |