Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Column.java 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*
  2. Copyright (c) 2005 Health Market Science, Inc.
  3. This library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Lesser General Public
  5. License as published by the Free Software Foundation; either
  6. version 2.1 of the License, or (at your option) any later version.
  7. This library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Lesser General Public License for more details.
  11. You should have received a copy of the GNU Lesser General Public
  12. License along with this library; if not, write to the Free Software
  13. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
  14. USA
  15. You can contact Health Market Science at info@healthmarketscience.com
  16. or at the following address:
  17. Health Market Science
  18. 2700 Horizon Drive
  19. Suite 200
  20. King of Prussia, PA 19406
  21. */
  22. package com.healthmarketscience.jackcess;
  23. import java.io.IOException;
  24. import java.nio.ByteBuffer;
  25. import java.nio.ByteOrder;
  26. import java.nio.CharBuffer;
  27. import java.sql.SQLException;
  28. import java.util.Calendar;
  29. import java.util.Date;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import java.util.TimeZone;
  33. import com.healthmarketscience.jackcess.scsu.EndOfInputException;
  34. import com.healthmarketscience.jackcess.scsu.Expand;
  35. import com.healthmarketscience.jackcess.scsu.IllegalInputException;
  36. import org.apache.commons.logging.Log;
  37. import org.apache.commons.logging.LogFactory;
  38. /**
  39. * Access database column definition
  40. * @author Tim McCune
  41. */
  42. public class Column implements Comparable {
  43. private static final Log LOG = LogFactory.getLog(Column.class);
  44. /**
  45. * Access starts counting dates at Jan 1, 1900. Java starts counting
  46. * at Jan 1, 1970. This is the # of days between them for conversion.
  47. */
  48. private static final double DAYS_BETWEEN_EPOCH_AND_1900 = 25569d;
  49. /**
  50. * Access stores numeric dates in days. Java stores them in milliseconds.
  51. */
  52. private static final double MILLISECONDS_PER_DAY = 86400000d;
  53. /**
  54. * Long value (LVAL) type that indicates that the value is stored on the same page
  55. */
  56. private static final short LONG_VALUE_TYPE_THIS_PAGE = (short) 0x8000;
  57. /**
  58. * Long value (LVAL) type that indicates that the value is stored on another page
  59. */
  60. private static final short LONG_VALUE_TYPE_OTHER_PAGE = (short) 0x4000;
  61. /**
  62. * Long value (LVAL) type that indicates that the value is stored on multiple other pages
  63. */
  64. private static final short LONG_VALUE_TYPE_OTHER_PAGES = (short) 0x0;
  65. /** For text columns, whether or not they are compressed */
  66. private boolean _compressedUnicode = false;
  67. /** Whether or not the column is of variable length */
  68. private boolean _variableLength;
  69. /** Numeric precision */
  70. private byte _precision;
  71. /** Numeric scale */
  72. private byte _scale;
  73. /** Data type */
  74. private byte _type;
  75. /** Format that the containing database is in */
  76. private JetFormat _format;
  77. /** Used to read in LVAL pages */
  78. private PageChannel _pageChannel;
  79. /** Maximum column length */
  80. private short _columnLength;
  81. /** 0-based column number */
  82. private short _columnNumber;
  83. /** Column name */
  84. private String _name;
  85. public Column() {
  86. this(JetFormat.VERSION_4);
  87. }
  88. public Column(JetFormat format) {
  89. _format = format;
  90. }
  91. /**
  92. * Read a column definition in from a buffer
  93. * @param buffer Buffer containing column definition
  94. * @param offset Offset in the buffer at which the column definition starts
  95. * @param format Format that the containing database is in
  96. */
  97. public Column(ByteBuffer buffer, int offset, PageChannel pageChannel, JetFormat format) {
  98. if (LOG.isDebugEnabled()) {
  99. LOG.debug("Column def block:\n" + ByteUtil.toHexString(buffer, offset, 25));
  100. }
  101. _pageChannel = pageChannel;
  102. _format = format;
  103. setType(buffer.get(offset + format.OFFSET_COLUMN_TYPE));
  104. _columnNumber = buffer.getShort(offset + format.OFFSET_COLUMN_NUMBER);
  105. _columnLength = buffer.getShort(offset + format.OFFSET_COLUMN_LENGTH);
  106. if (_type == DataTypes.NUMERIC) {
  107. _precision = buffer.get(offset + format.OFFSET_COLUMN_PRECISION);
  108. _scale = buffer.get(offset + format.OFFSET_COLUMN_SCALE);
  109. }
  110. _variableLength = ((buffer.get(offset + format.OFFSET_COLUMN_VARIABLE)
  111. & 1) != 1);
  112. _compressedUnicode = ((buffer.get(offset +
  113. format.OFFSET_COLUMN_COMPRESSED_UNICODE) & 1) == 1);
  114. }
  115. public String getName() {
  116. return _name;
  117. }
  118. public void setName(String name) {
  119. _name = name;
  120. }
  121. public boolean isVariableLength() {
  122. return _variableLength;
  123. }
  124. public void setVariableLength(boolean variableLength) {
  125. _variableLength = variableLength;
  126. }
  127. public short getColumnNumber() {
  128. return _columnNumber;
  129. }
  130. /**
  131. * Also sets the length and the variable length flag, inferred from the type
  132. */
  133. public void setType(byte type) {
  134. _type = type;
  135. setLength((short) size());
  136. switch (type) {
  137. case DataTypes.BOOLEAN:
  138. case DataTypes.BYTE:
  139. case DataTypes.INT:
  140. case DataTypes.LONG:
  141. case DataTypes.DOUBLE:
  142. case DataTypes.FLOAT:
  143. case DataTypes.SHORT_DATE_TIME:
  144. setVariableLength(false);
  145. break;
  146. case DataTypes.BINARY:
  147. case DataTypes.TEXT:
  148. setVariableLength(true);
  149. break;
  150. }
  151. }
  152. public byte getType() {
  153. return _type;
  154. }
  155. public int getSQLType() throws SQLException {
  156. return DataTypes.toSQLType(_type);
  157. }
  158. public void setSQLType(int type) throws SQLException {
  159. setType(DataTypes.fromSQLType(type));
  160. }
  161. public boolean isCompressedUnicode() {
  162. return _compressedUnicode;
  163. }
  164. public byte getPrecision() {
  165. return _precision;
  166. }
  167. public byte getScale() {
  168. return _scale;
  169. }
  170. public void setLength(short length) {
  171. _columnLength = length;
  172. }
  173. public short getLength() {
  174. return _columnLength;
  175. }
  176. /**
  177. * Deserialize a raw byte value for this column into an Object
  178. * @param data The raw byte value
  179. * @return The deserialized Object
  180. */
  181. public Object read(byte[] data) throws IOException {
  182. return read(data, ByteOrder.LITTLE_ENDIAN);
  183. }
  184. /**
  185. * Deserialize a raw byte value for this column into an Object
  186. * @param data The raw byte value
  187. * @param order Byte order in which the raw value is stored
  188. * @return The deserialized Object
  189. */
  190. public Object read(byte[] data, ByteOrder order) throws IOException {
  191. ByteBuffer buffer = ByteBuffer.wrap(data);
  192. buffer.order(order);
  193. switch (_type) {
  194. case DataTypes.BOOLEAN:
  195. throw new IOException("Tried to read a boolean from data instead of null mask.");
  196. case DataTypes.BYTE:
  197. return new Byte(buffer.get());
  198. case DataTypes.INT:
  199. return new Short(buffer.getShort());
  200. case DataTypes.LONG:
  201. return new Integer(buffer.getInt());
  202. case DataTypes.DOUBLE:
  203. return new Double(buffer.getDouble());
  204. case DataTypes.FLOAT:
  205. return new Float(buffer.getFloat());
  206. case DataTypes.SHORT_DATE_TIME:
  207. long time = (long) ((buffer.getDouble() - DAYS_BETWEEN_EPOCH_AND_1900) *
  208. MILLISECONDS_PER_DAY);
  209. Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
  210. cal.setTimeInMillis(time);
  211. //Not sure why we're off by 1...
  212. cal.add(Calendar.DATE, 1);
  213. return cal.getTime();
  214. case DataTypes.BINARY:
  215. return data;
  216. case DataTypes.TEXT:
  217. if (_compressedUnicode) {
  218. try {
  219. String rtn = new Expand().expand(data);
  220. //SCSU expander isn't handling the UTF-8-looking 2-byte combo that
  221. //prepends some of these strings. Rather than dig into that code,
  222. //I'm just stripping them off here. However, this is probably not
  223. //a great idea.
  224. if (rtn.length() > 2 && (int) rtn.charAt(0) == 255 &&
  225. (int) rtn.charAt(1) == 254)
  226. {
  227. rtn = rtn.substring(2);
  228. }
  229. //It also isn't handling short strings.
  230. if (rtn.length() > 1 && (int) rtn.charAt(1) == 0) {
  231. char[] fixed = new char[rtn.length() / 2];
  232. for (int i = 0; i < fixed.length; i ++) {
  233. fixed[i] = rtn.charAt(i * 2);
  234. }
  235. rtn = new String(fixed);
  236. }
  237. return rtn;
  238. } catch (IllegalInputException e) {
  239. throw new IOException("Can't expand text column");
  240. } catch (EndOfInputException e) {
  241. throw new IOException("Can't expand text column");
  242. }
  243. } else {
  244. return _format.CHARSET.decode(ByteBuffer.wrap(data)).toString();
  245. }
  246. case DataTypes.MONEY:
  247. //XXX
  248. return null;
  249. case DataTypes.OLE:
  250. if (data.length > 0) {
  251. return getLongValue(data);
  252. } else {
  253. return null;
  254. }
  255. case DataTypes.MEMO:
  256. if (data.length > 0) {
  257. return _format.CHARSET.decode(ByteBuffer.wrap(getLongValue(data))).toString();
  258. } else {
  259. return null;
  260. }
  261. case DataTypes.NUMERIC:
  262. //XXX
  263. return null;
  264. case DataTypes.UNKNOWN_0D:
  265. case DataTypes.GUID:
  266. return null;
  267. default:
  268. throw new IOException("Unrecognized data type: " + _type);
  269. }
  270. }
  271. /**
  272. * @param lvalDefinition Column value that points to an LVAL record
  273. * @return The LVAL data
  274. */
  275. private byte[] getLongValue(byte[] lvalDefinition) throws IOException {
  276. ByteBuffer def = ByteBuffer.wrap(lvalDefinition);
  277. def.order(ByteOrder.LITTLE_ENDIAN);
  278. short length = def.getShort();
  279. byte[] rtn = new byte[length];
  280. short type = def.getShort();
  281. switch (type) {
  282. case LONG_VALUE_TYPE_OTHER_PAGE:
  283. if (lvalDefinition.length != _format.SIZE_LONG_VALUE_DEF) {
  284. throw new IOException("Expected " + _format.SIZE_LONG_VALUE_DEF +
  285. " bytes in long value definition, but found " + lvalDefinition.length);
  286. }
  287. byte rowNum = def.get();
  288. int pageNum = ByteUtil.get3ByteInt(def, def.position());
  289. ByteBuffer lvalPage = _pageChannel.createPageBuffer();
  290. _pageChannel.readPage(lvalPage, pageNum);
  291. short offset = lvalPage.getShort(14 +
  292. rowNum * _format.SIZE_ROW_LOCATION);
  293. lvalPage.position(offset);
  294. lvalPage.get(rtn);
  295. break;
  296. case LONG_VALUE_TYPE_THIS_PAGE:
  297. def.getLong(); //Skip over lval_dp and unknown
  298. def.get(rtn);
  299. case LONG_VALUE_TYPE_OTHER_PAGES:
  300. //XXX
  301. return null;
  302. default:
  303. throw new IOException("Unrecognized long value type: " + type);
  304. }
  305. return rtn;
  306. }
  307. /**
  308. * Write an LVAL column into a ByteBuffer inline (LONG_VALUE_TYPE_THIS_PAGE)
  309. * @param value Value of the LVAL column
  310. * @return A buffer containing the LVAL definition and the column value
  311. */
  312. public ByteBuffer writeLongValue(byte[] value) throws IOException {
  313. ByteBuffer def = ByteBuffer.allocate(_format.SIZE_LONG_VALUE_DEF + value.length);
  314. def.order(ByteOrder.LITTLE_ENDIAN);
  315. def.putShort((short) value.length);
  316. def.putShort(LONG_VALUE_TYPE_THIS_PAGE);
  317. def.putInt(0);
  318. def.putInt(0); //Unknown
  319. def.put(value);
  320. def.flip();
  321. return def;
  322. }
  323. /**
  324. * Write an LVAL column into a ByteBuffer on another page
  325. * (LONG_VALUE_TYPE_OTHER_PAGE)
  326. * @param value Value of the LVAL column
  327. * @return A buffer containing the LVAL definition
  328. */
  329. public ByteBuffer writeLongValueInNewPage(byte[] value) throws IOException {
  330. ByteBuffer lvalPage = _pageChannel.createPageBuffer();
  331. lvalPage.put(PageTypes.DATA); //Page type
  332. lvalPage.put((byte) 1); //Unknown
  333. lvalPage.putShort((short) (_format.PAGE_SIZE -
  334. _format.OFFSET_LVAL_ROW_LOCATION_BLOCK - _format.SIZE_ROW_LOCATION -
  335. value.length)); //Free space
  336. lvalPage.put((byte) 'L');
  337. lvalPage.put((byte) 'V');
  338. lvalPage.put((byte) 'A');
  339. lvalPage.put((byte) 'L');
  340. int offset = _format.PAGE_SIZE - value.length;
  341. lvalPage.position(14);
  342. lvalPage.putShort((short) offset);
  343. lvalPage.position(offset);
  344. lvalPage.put(value);
  345. ByteBuffer def = ByteBuffer.allocate(_format.SIZE_LONG_VALUE_DEF);
  346. def.order(ByteOrder.LITTLE_ENDIAN);
  347. def.putShort((short) value.length);
  348. def.putShort(LONG_VALUE_TYPE_OTHER_PAGE);
  349. def.put((byte) 0); //Row number
  350. def.put(ByteUtil.to3ByteInt(_pageChannel.writeNewPage(lvalPage))); //Page #
  351. def.putInt(0); //Unknown
  352. def.flip();
  353. return def;
  354. }
  355. /**
  356. * Serialize an Object into a raw byte value for this column in little endian order
  357. * @param obj Object to serialize
  358. * @return A buffer containing the bytes
  359. */
  360. public ByteBuffer write(Object obj) throws IOException {
  361. return write(obj, ByteOrder.LITTLE_ENDIAN);
  362. }
  363. /**
  364. * Serialize an Object into a raw byte value for this column
  365. * @param obj Object to serialize
  366. * @param order Order in which to serialize
  367. * @return A buffer containing the bytes
  368. */
  369. public ByteBuffer write(Object obj, ByteOrder order) throws IOException {
  370. int size = size();
  371. if (_type == DataTypes.OLE || _type == DataTypes.MEMO) {
  372. size += ((byte[]) obj).length;
  373. }
  374. if (_type == DataTypes.TEXT) {
  375. size = getLength();
  376. }
  377. ByteBuffer buffer = ByteBuffer.allocate(size);
  378. buffer.order(order);
  379. switch (_type) {
  380. case DataTypes.BOOLEAN:
  381. break;
  382. case DataTypes.BYTE:
  383. buffer.put(((Byte) obj).byteValue());
  384. break;
  385. case DataTypes.INT:
  386. buffer.putShort(((Short) obj).shortValue());
  387. break;
  388. case DataTypes.LONG:
  389. buffer.putInt(((Integer) obj).intValue());
  390. break;
  391. case DataTypes.DOUBLE:
  392. buffer.putDouble(((Double) obj).doubleValue());
  393. break;
  394. case DataTypes.FLOAT:
  395. buffer.putFloat(((Float) obj).floatValue());
  396. break;
  397. case DataTypes.SHORT_DATE_TIME:
  398. Calendar cal = Calendar.getInstance();
  399. cal.setTime((Date) obj);
  400. long ms = cal.getTimeInMillis();
  401. ms += (long) TimeZone.getDefault().getOffset(ms);
  402. buffer.putDouble((double) ms / MILLISECONDS_PER_DAY +
  403. DAYS_BETWEEN_EPOCH_AND_1900);
  404. break;
  405. case DataTypes.BINARY:
  406. buffer.put((byte[]) obj);
  407. break;
  408. case DataTypes.TEXT:
  409. CharSequence text = (CharSequence) obj;
  410. int maxChars = size / 2;
  411. if (text.length() > maxChars) {
  412. text = text.subSequence(0, maxChars);
  413. }
  414. buffer.put(encodeText(text));
  415. break;
  416. case DataTypes.OLE:
  417. buffer.put(writeLongValue((byte[]) obj));
  418. break;
  419. case DataTypes.MEMO:
  420. buffer.put(writeLongValue(encodeText((CharSequence) obj).array()));
  421. break;
  422. default:
  423. throw new IOException("Unsupported data type: " + _type);
  424. }
  425. buffer.flip();
  426. return buffer;
  427. }
  428. /**
  429. * @param text Text to encode
  430. * @return A buffer with the text encoded
  431. */
  432. private ByteBuffer encodeText(CharSequence text) {
  433. return _format.CHARSET.encode(CharBuffer.wrap(text));
  434. }
  435. /**
  436. * @return Number of bytes that should be read for this column
  437. * (applies to fixed-width columns)
  438. */
  439. public int size() {
  440. switch (_type) {
  441. case DataTypes.BOOLEAN:
  442. return 0;
  443. case DataTypes.BYTE:
  444. return 1;
  445. case DataTypes.INT:
  446. return 2;
  447. case DataTypes.LONG:
  448. return 4;
  449. case DataTypes.MONEY:
  450. case DataTypes.DOUBLE:
  451. return 8;
  452. case DataTypes.FLOAT:
  453. return 4;
  454. case DataTypes.SHORT_DATE_TIME:
  455. return 8;
  456. case DataTypes.BINARY:
  457. return 255;
  458. case DataTypes.TEXT:
  459. return 50 * 2;
  460. case DataTypes.OLE:
  461. return _format.SIZE_LONG_VALUE_DEF;
  462. case DataTypes.MEMO:
  463. return _format.SIZE_LONG_VALUE_DEF;
  464. case DataTypes.NUMERIC:
  465. throw new IllegalArgumentException("FIX ME");
  466. case DataTypes.UNKNOWN_0D:
  467. case DataTypes.GUID:
  468. throw new IllegalArgumentException("FIX ME");
  469. default:
  470. throw new IllegalArgumentException("Unrecognized data type: " + _type);
  471. }
  472. }
  473. public String toString() {
  474. StringBuffer rtn = new StringBuffer();
  475. rtn.append("\tName: " + _name);
  476. rtn.append("\n\tType: 0x" + Integer.toHexString((int)_type));
  477. rtn.append("\n\tNumber: " + _columnNumber);
  478. rtn.append("\n\tLength: " + _columnLength);
  479. rtn.append("\n\tVariable length: " + _variableLength);
  480. rtn.append("\n\tCompressed Unicode: " + _compressedUnicode);
  481. rtn.append("\n\n");
  482. return rtn.toString();
  483. }
  484. public int compareTo(Object obj) {
  485. Column other = (Column) obj;
  486. if (_columnNumber > other.getColumnNumber()) {
  487. return 1;
  488. } else if (_columnNumber < other.getColumnNumber()) {
  489. return -1;
  490. } else {
  491. return 0;
  492. }
  493. }
  494. /**
  495. * @param columns A list of columns in a table definition
  496. * @return The number of variable length columns found in the list
  497. */
  498. public static short countVariableLength(List columns) {
  499. short rtn = 0;
  500. Iterator iter = columns.iterator();
  501. while (iter.hasNext()) {
  502. Column col = (Column) iter.next();
  503. if (col.isVariableLength()) {
  504. rtn++;
  505. }
  506. }
  507. return rtn;
  508. }
  509. }