Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

TableBuilder.java 8.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /*
  2. Copyright (c) 2008 Health Market Science, Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess;
  14. import java.io.IOException;
  15. import java.util.ArrayList;
  16. import java.util.Arrays;
  17. import java.util.Collection;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.List;
  21. import java.util.Map;
  22. import java.util.Set;
  23. import com.healthmarketscience.jackcess.impl.DatabaseImpl;
  24. import com.healthmarketscience.jackcess.impl.PropertyMapImpl;
  25. import com.healthmarketscience.jackcess.impl.TableCreator;
  26. /**
  27. * Builder style class for constructing a {@link Table}.
  28. * <p>
  29. * Example:
  30. * <pre>
  31. * Table table = new TableBuilder("Test")
  32. * .addColumn(new ColumnBuilder("ID", DataType.LONG)
  33. * .setAutoNumber(true))
  34. * .addColumn(new ColumnBuilder("Name", DataType.TEXT))
  35. * .addIndex(new IndexBuilder(IndexBuilder.PRIMARY_KEY_NAME)
  36. * .addColumns("ID").setPrimaryKey())
  37. * .toTable(db);
  38. * </pre>
  39. *
  40. * @author James Ahlborn
  41. * @see ColumnBuilder
  42. * @see IndexBuilder
  43. * @see RelationshipBuilder
  44. * @usage _general_class_
  45. */
  46. public class TableBuilder {
  47. /** Prefix for column or table names that are reserved words */
  48. private static final String ESCAPE_PREFIX = "x";
  49. /* nested class for lazy loading */
  50. private static final class ReservedWords {
  51. /**
  52. * All of the reserved words in Access that should be escaped when creating
  53. * table or column names
  54. */
  55. private static final Set<String> VALUES =
  56. new HashSet<String>(Arrays.asList(
  57. "add", "all", "alphanumeric", "alter", "and", "any", "application", "as",
  58. "asc", "assistant", "autoincrement", "avg", "between", "binary", "bit",
  59. "boolean", "by", "byte", "char", "character", "column", "compactdatabase",
  60. "constraint", "container", "count", "counter", "create", "createdatabase",
  61. "createfield", "creategroup", "createindex", "createobject", "createproperty",
  62. "createrelation", "createtabledef", "createuser", "createworkspace",
  63. "currency", "currentuser", "database", "date", "datetime", "delete",
  64. "desc", "description", "disallow", "distinct", "distinctrow", "document",
  65. "double", "drop", "echo", "else", "end", "eqv", "error", "exists", "exit",
  66. "false", "field", "fields", "fillcache", "float", "float4", "float8",
  67. "foreign", "form", "forms", "from", "full", "function", "general",
  68. "getobject", "getoption", "gotopage", "group", "group by", "guid", "having",
  69. "idle", "ieeedouble", "ieeesingle", "if", "ignore", "imp", "in", "index",
  70. "indexes", "inner", "insert", "inserttext", "int", "integer", "integer1",
  71. "integer2", "integer4", "into", "is", "join", "key", "lastmodified", "left",
  72. "level", "like", "logical", "logical1", "long", "longbinary", "longtext",
  73. "macro", "match", "max", "min", "mod", "memo", "module", "money", "move",
  74. "name", "newpassword", "no", "not", "null", "number", "numeric", "object",
  75. "oleobject", "off", "on", "openrecordset", "option", "or", "order", "outer",
  76. "owneraccess", "parameter", "parameters", "partial", "percent", "pivot",
  77. "primary", "procedure", "property", "queries", "query", "quit", "real",
  78. "recalc", "recordset", "references", "refresh", "refreshlink",
  79. "registerdatabase", "relation", "repaint", "repairdatabase", "report",
  80. "reports", "requery", "right", "screen", "section", "select", "set",
  81. "setfocus", "setoption", "short", "single", "smallint", "some", "sql",
  82. "stdev", "stdevp", "string", "sum", "table", "tabledef", "tabledefs",
  83. "tableid", "text", "time", "timestamp", "top", "transform", "true", "type",
  84. "union", "unique", "update", "user", "value", "values", "var", "varp",
  85. "varbinary", "varchar", "where", "with", "workspace", "xor", "year", "yes",
  86. "yesno"));
  87. }
  88. /** name of the new table */
  89. private String _name;
  90. /** columns for the new table */
  91. private List<ColumnBuilder> _columns = new ArrayList<ColumnBuilder>();
  92. /** indexes for the new table */
  93. private List<IndexBuilder> _indexes = new ArrayList<IndexBuilder>();
  94. /** whether or not table/column/index names are automatically escaped */
  95. private boolean _escapeIdentifiers;
  96. /** table properties (if any) */
  97. private Map<String,PropertyMap.Property> _props;
  98. public TableBuilder(String name) {
  99. this(name, false);
  100. }
  101. public TableBuilder(String name, boolean escapeIdentifiers) {
  102. _name = name;
  103. _escapeIdentifiers = escapeIdentifiers;
  104. if(_escapeIdentifiers) {
  105. _name = escapeIdentifier(_name);
  106. }
  107. }
  108. public String getName() {
  109. return _name;
  110. }
  111. /**
  112. * Adds a Column to the new table.
  113. */
  114. public TableBuilder addColumn(ColumnBuilder column) {
  115. if(_escapeIdentifiers) {
  116. column.escapeName();
  117. }
  118. _columns.add(column);
  119. return this;
  120. }
  121. /**
  122. * Adds the Columns to the new table.
  123. */
  124. public TableBuilder addColumns(Collection<? extends ColumnBuilder> columns) {
  125. if(columns != null) {
  126. for(ColumnBuilder col : columns) {
  127. addColumn(col);
  128. }
  129. }
  130. return this;
  131. }
  132. public List<ColumnBuilder> getColumns() {
  133. return _columns;
  134. }
  135. /**
  136. * Adds an IndexBuilder to the new table.
  137. */
  138. public TableBuilder addIndex(IndexBuilder index) {
  139. if(_escapeIdentifiers) {
  140. index.setName(escapeIdentifier(index.getName()));
  141. for(IndexBuilder.Column col : index.getColumns()) {
  142. col.setName(escapeIdentifier(col.getName()));
  143. }
  144. }
  145. _indexes.add(index);
  146. return this;
  147. }
  148. /**
  149. * Adds the Indexes to the new table.
  150. */
  151. public TableBuilder addIndexes(Collection<? extends IndexBuilder> indexes) {
  152. if(indexes != null) {
  153. for(IndexBuilder col : indexes) {
  154. addIndex(col);
  155. }
  156. }
  157. return this;
  158. }
  159. public List<IndexBuilder> getIndexes() {
  160. return _indexes;
  161. }
  162. /**
  163. * Sets whether or not subsequently added columns will have their names
  164. * automatically escaped
  165. */
  166. public TableBuilder setEscapeIdentifiers(boolean escapeIdentifiers) {
  167. _escapeIdentifiers = escapeIdentifiers;
  168. return this;
  169. }
  170. /**
  171. * Sets the names of the primary key columns for this table. Convenience
  172. * method for creating a primary key index on a table.
  173. */
  174. public TableBuilder setPrimaryKey(String... colNames) {
  175. addIndex(new IndexBuilder(IndexBuilder.PRIMARY_KEY_NAME)
  176. .addColumns(colNames).setPrimaryKey());
  177. return this;
  178. }
  179. /**
  180. * Escapes the new table's name using {@link TableBuilder#escapeIdentifier}.
  181. */
  182. public TableBuilder escapeName() {
  183. _name = escapeIdentifier(_name);
  184. return this;
  185. }
  186. /**
  187. * Sets the table property with the given name to the given value. Attempts
  188. * to determine the type of the property (see
  189. * {@link PropertyMap#put(String,Object)} for details on determining the
  190. * property type).
  191. */
  192. public TableBuilder putProperty(String name, Object value) {
  193. return putProperty(name, null, value);
  194. }
  195. /**
  196. * Sets the table property with the given name and type to the given value.
  197. */
  198. public TableBuilder putProperty(String name, DataType type, Object value) {
  199. if(_props == null) {
  200. _props = new HashMap<String,PropertyMap.Property>();
  201. }
  202. _props.put(name, PropertyMapImpl.createProperty(name, type, value));
  203. return this;
  204. }
  205. public Map<String,PropertyMap.Property> getProperties() {
  206. return _props;
  207. }
  208. /**
  209. * Creates a new Table in the given Database with the currently configured
  210. * attributes.
  211. */
  212. public Table toTable(Database db) throws IOException {
  213. return new TableCreator(((DatabaseImpl)db)).createTable(this);
  214. }
  215. /**
  216. * @return A table or column name escaped for Access
  217. * @usage _general_method_
  218. */
  219. public static String escapeIdentifier(String s) {
  220. if (isReservedWord(s)) {
  221. return ESCAPE_PREFIX + s;
  222. }
  223. return s;
  224. }
  225. /**
  226. * @return {@code true} if the given string is a reserved word,
  227. * {@code false} otherwise
  228. * @usage _general_method_
  229. */
  230. public static boolean isReservedWord(String s) {
  231. return ReservedWords.VALUES.contains(s.toLowerCase());
  232. }
  233. }