選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

TableBuilder.java 8.4KB

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