Debian Codegraph @

src/main/org/h2/command/ddl/CreateSynonym.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.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.message.DbException;
13 import org.h2.schema.Schema;
14 import org.h2.table.TableSynonym;
15
16 /**
17 * This class represents the statement
18 * CREATE SYNONYM
19 */
20 public class CreateSynonym extends SchemaOwnerCommand {
21
22 private final CreateSynonymData data = new CreateSynonymData();
23 private boolean ifNotExists;
24 private boolean orReplace;
25 private String comment;
26
27 public CreateSynonym(SessionLocal session, Schema schema) {
28 super(session, schema);
29 }
30
31 public void setName(String name) {
32 data.synonymName = name;
33 }
34
35 public void setSynonymFor(String tableName) {
36 data.synonymFor = tableName;
37 }
38
39 public void setSynonymForSchema(Schema synonymForSchema) {
40 data.synonymForSchema = synonymForSchema;
41 }
42
43 public void setIfNotExists(boolean ifNotExists) {
44 this.ifNotExists = ifNotExists;
45 }
46
47 public void setOrReplace(boolean orReplace) { this.orReplace = orReplace; }
48
49 @Override
50 long update(Schema schema) {
51 Database db = getDatabase();
52 data.session = session;
53 db.lockMeta(session);
54
55 if (schema.findTableOrView(session, data.synonymName) != null) {
56 throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.synonymName);
57 }
58
59 if (data.synonymForSchema.findTableOrView(session, data.synonymFor) != null) {
60 return createTableSynonym(db);
61 }
62
63 throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1,
64 data.synonymForSchema.getName() + "." + data.synonymFor);
65
66 }
67
68 private int createTableSynonym(Database db) {
69
70 TableSynonym old = getSchema().getSynonym(data.synonymName);
71 if (old != null) {
72 if (orReplace) {
73 // ok, we replacing the existing synonym
74 } else if (ifNotExists) {
75 return 0;
76 } else {
77 throw DbException.get(ErrorCode.TABLE_OR_VIEW_ALREADY_EXISTS_1, data.synonymName);
78 }
79 }
80
81 TableSynonym table;
82 if (old != null) {
83 table = old;
84 data.schema = table.getSchema();
85 table.updateData(data);
86 table.setComment(comment);
87 table.setModified();
88 db.updateMeta(session, table);
89 } else {
90 data.id = getObjectId();
91 table = getSchema().createSynonym(data);
92 table.setComment(comment);
93 db.addSchemaObject(session, table);
94 }
95
96 table.updateSynonymFor();
97 return 0;
98 }
99
100 public void setComment(String comment) {
101 this.comment = comment;
102 }
103
104 @Override
105 public int getType() {
106 return CommandInterface.CREATE_SYNONYM;
107 }
108
109
110 }