01: /*
02: * TableAlias.java
03: *
04: * This file is part of SQL Workbench/J, http://www.sql-workbench.net
05: *
06: * Copyright 2002-2008, Thomas Kellerer
07: * No part of this code maybe reused without the permission of the author
08: *
09: * To contact the author please send an email to: support@sql-workbench.net
10: *
11: */
12: package workbench.util;
13:
14: import workbench.db.TableIdentifier;
15:
16: /**
17: * @author support@sql-workbench.net
18: */
19: public class TableAlias {
20: private final TableIdentifier table;
21: private final String alias;
22: private String display;
23:
24: public TableAlias(String value) {
25: if (StringUtil.isEmptyString(value))
26: throw new IllegalArgumentException(
27: "Identifier must not be empty");
28:
29: String tablename = null;
30: String[] words = value.split("\\s");
31:
32: if (words.length > 0) {
33: tablename = words[0].trim();
34: }
35:
36: if (words.length == 2) {
37: alias = words[1].trim();
38: } else if (words.length == 3) {
39: // Assuming "table AS t1" syntax
40: if (words[1].equalsIgnoreCase("as")) {
41: alias = words[2].trim();
42: } else {
43: alias = words[1].trim();
44: }
45: } else {
46: this .alias = null;
47: }
48:
49: this .table = new TableIdentifier(tablename);
50:
51: }
52:
53: public final String getAlias() {
54: return this .alias;
55: }
56:
57: public final TableIdentifier getTable() {
58: return this .table;
59: }
60:
61: public final String getNameToUse() {
62: if (alias == null)
63: return table.getTableName();
64: return alias;
65: }
66:
67: public String toString() {
68: if (display == null) {
69: if (alias == null)
70: display = table.getTableName();
71: else
72: display = alias + " (" + table + ")";
73: }
74: return display;
75: }
76:
77: /**
78: * Compares the given name to this TableAlias checking
79: * if the name either references this table or its alias
80: */
81: public boolean isTableOrAlias(String name) {
82: if (StringUtil.isEmptyString(name))
83: return false;
84:
85: TableIdentifier tbl = new TableIdentifier(name);
86: return (table.getTableName().equalsIgnoreCase(
87: tbl.getTableName()) || name.equalsIgnoreCase(alias));
88: }
89: }
|