You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ColumnImpl.java 64KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192
  1. /*
  2. Copyright (c) 2005 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.impl;
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.IOException;
  16. import java.io.InputStream;
  17. import java.io.ObjectOutputStream;
  18. import java.io.ObjectStreamException;
  19. import java.io.Reader;
  20. import java.io.Serializable;
  21. import java.math.BigDecimal;
  22. import java.math.BigInteger;
  23. import java.nio.ByteBuffer;
  24. import java.nio.ByteOrder;
  25. import java.nio.CharBuffer;
  26. import java.nio.charset.Charset;
  27. import java.sql.Blob;
  28. import java.sql.Clob;
  29. import java.sql.SQLException;
  30. import java.util.Calendar;
  31. import java.util.Collection;
  32. import java.util.Date;
  33. import java.util.List;
  34. import java.util.Map;
  35. import java.util.UUID;
  36. import java.util.regex.Matcher;
  37. import java.util.regex.Pattern;
  38. import com.healthmarketscience.jackcess.Column;
  39. import com.healthmarketscience.jackcess.ColumnBuilder;
  40. import com.healthmarketscience.jackcess.DataType;
  41. import com.healthmarketscience.jackcess.PropertyMap;
  42. import com.healthmarketscience.jackcess.Table;
  43. import com.healthmarketscience.jackcess.complex.ComplexColumnInfo;
  44. import com.healthmarketscience.jackcess.complex.ComplexValue;
  45. import com.healthmarketscience.jackcess.complex.ComplexValueForeignKey;
  46. import com.healthmarketscience.jackcess.impl.complex.ComplexValueForeignKeyImpl;
  47. import com.healthmarketscience.jackcess.util.ColumnValidator;
  48. import com.healthmarketscience.jackcess.util.SimpleColumnValidator;
  49. import org.apache.commons.lang.builder.ToStringBuilder;
  50. import org.apache.commons.logging.Log;
  51. import org.apache.commons.logging.LogFactory;
  52. /**
  53. * Access database column definition
  54. * @author Tim McCune
  55. * @usage _intermediate_class_
  56. */
  57. public class ColumnImpl implements Column, Comparable<ColumnImpl> {
  58. protected static final Log LOG = LogFactory.getLog(ColumnImpl.class);
  59. /**
  60. * Placeholder object for adding rows which indicates that the caller wants
  61. * the RowId of the new row. Must be added as an extra value at the end of
  62. * the row values array.
  63. * @see TableImpl#asRowWithRowId
  64. * @usage _intermediate_field_
  65. */
  66. public static final Object RETURN_ROW_ID = "<RETURN_ROW_ID>";
  67. /**
  68. * Access stores numeric dates in days. Java stores them in milliseconds.
  69. */
  70. private static final long MILLISECONDS_PER_DAY =
  71. (24L * 60L * 60L * 1000L);
  72. /**
  73. * Access starts counting dates at Dec 30, 1899 (note, this strange date
  74. * seems to be caused by MS compatibility with Lotus-1-2-3 and incorrect
  75. * leap years). Java starts counting at Jan 1, 1970. This is the # of
  76. * millis between them for conversion.
  77. */
  78. static final long MILLIS_BETWEEN_EPOCH_AND_1900 =
  79. 25569L * MILLISECONDS_PER_DAY;
  80. /**
  81. * mask for the fixed len bit
  82. * @usage _advanced_field_
  83. */
  84. public static final byte FIXED_LEN_FLAG_MASK = (byte)0x01;
  85. /**
  86. * mask for the auto number bit
  87. * @usage _advanced_field_
  88. */
  89. public static final byte AUTO_NUMBER_FLAG_MASK = (byte)0x04;
  90. /**
  91. * mask for the auto number guid bit
  92. * @usage _advanced_field_
  93. */
  94. public static final byte AUTO_NUMBER_GUID_FLAG_MASK = (byte)0x40;
  95. /**
  96. * mask for the hyperlink bit (on memo types)
  97. * @usage _advanced_field_
  98. */
  99. public static final byte HYPERLINK_FLAG_MASK = (byte)0x80;
  100. /**
  101. * mask for the "is updatable" field bit
  102. * @usage _advanced_field_
  103. */
  104. public static final byte UPDATABLE_FLAG_MASK = (byte)0x02;
  105. // some other flags?
  106. // 0x10: replication related field (or hidden?)
  107. protected static final byte COMPRESSED_UNICODE_EXT_FLAG_MASK = (byte)0x01;
  108. private static final byte CALCULATED_EXT_FLAG_MASK = (byte)0xC0;
  109. static final byte NUMERIC_NEGATIVE_BYTE = (byte)0x80;
  110. /** the value for the "general" sort order */
  111. private static final short GENERAL_SORT_ORDER_VALUE = 1033;
  112. /**
  113. * the "general" text sort order, legacy version (access 2000-2007)
  114. * @usage _intermediate_field_
  115. */
  116. public static final SortOrder GENERAL_LEGACY_SORT_ORDER =
  117. new SortOrder(GENERAL_SORT_ORDER_VALUE, (byte)0);
  118. /**
  119. * the "general" text sort order, latest version (access 2010+)
  120. * @usage _intermediate_field_
  121. */
  122. public static final SortOrder GENERAL_SORT_ORDER =
  123. new SortOrder(GENERAL_SORT_ORDER_VALUE, (byte)1);
  124. /** pattern matching textual guid strings (allows for optional surrounding
  125. '{' and '}') */
  126. private static final Pattern GUID_PATTERN = Pattern.compile("\\s*[{]?([\\p{XDigit}]{8})-([\\p{XDigit}]{4})-([\\p{XDigit}]{4})-([\\p{XDigit}]{4})-([\\p{XDigit}]{12})[}]?\\s*");
  127. /** header used to indicate unicode text compression */
  128. private static final byte[] TEXT_COMPRESSION_HEADER =
  129. { (byte)0xFF, (byte)0XFE };
  130. private static final char MIN_COMPRESS_CHAR = 1;
  131. private static final char MAX_COMPRESS_CHAR = 0xFF;
  132. /** auto numbers must be > 0 */
  133. static final int INVALID_AUTO_NUMBER = 0;
  134. /** owning table */
  135. private final TableImpl _table;
  136. /** Whether or not the column is of variable length */
  137. private final boolean _variableLength;
  138. /** Whether or not the column is an autonumber column */
  139. private final boolean _autoNumber;
  140. /** Whether or not the column is a calculated column */
  141. private final boolean _calculated;
  142. /** Data type */
  143. private final DataType _type;
  144. /** Maximum column length */
  145. private final short _columnLength;
  146. /** 0-based column number */
  147. private final short _columnNumber;
  148. /** index of the data for this column within a list of row data */
  149. private int _columnIndex;
  150. /** display index of the data for this column */
  151. private final int _displayIndex;
  152. /** Column name */
  153. private final String _name;
  154. /** the offset of the fixed data in the row */
  155. private final int _fixedDataOffset;
  156. /** the index of the variable length data in the var len offset table */
  157. private final int _varLenTableIndex;
  158. /** the auto number generator for this column (if autonumber column) */
  159. private final AutoNumberGenerator _autoNumberGenerator;
  160. /** properties for this column, if any */
  161. private PropertyMap _props;
  162. /** Validator for writing new values */
  163. private ColumnValidator _validator = SimpleColumnValidator.INSTANCE;
  164. /**
  165. * @usage _advanced_method_
  166. */
  167. protected ColumnImpl(TableImpl table, String name, DataType type,
  168. int colNumber, int fixedOffset, int varLenIndex) {
  169. _table = table;
  170. _name = name;
  171. _type = type;
  172. if(!_type.isVariableLength()) {
  173. _columnLength = (short)type.getFixedSize();
  174. } else {
  175. _columnLength = (short)type.getMaxSize();
  176. }
  177. _variableLength = type.isVariableLength();
  178. _autoNumber = false;
  179. _calculated = false;
  180. _autoNumberGenerator = null;
  181. _columnNumber = (short)colNumber;
  182. _columnIndex = colNumber;
  183. _displayIndex = colNumber;
  184. _fixedDataOffset = fixedOffset;
  185. _varLenTableIndex = varLenIndex;
  186. }
  187. /**
  188. * Read a column definition in from a buffer
  189. * @usage _advanced_method_
  190. */
  191. ColumnImpl(InitArgs args)
  192. throws IOException
  193. {
  194. _table = args.table;
  195. _name = args.name;
  196. _displayIndex = args.displayIndex;
  197. _type = args.type;
  198. _columnNumber = args.buffer.getShort(
  199. args.offset + getFormat().OFFSET_COLUMN_NUMBER);
  200. _columnLength = args.buffer.getShort(
  201. args.offset + getFormat().OFFSET_COLUMN_LENGTH);
  202. _variableLength = ((args.flags & FIXED_LEN_FLAG_MASK) == 0);
  203. _autoNumber = ((args.flags &
  204. (AUTO_NUMBER_FLAG_MASK | AUTO_NUMBER_GUID_FLAG_MASK)) != 0);
  205. _calculated = ((args.extFlags & CALCULATED_EXT_FLAG_MASK) != 0);
  206. _autoNumberGenerator = createAutoNumberGenerator();
  207. if(_variableLength) {
  208. _varLenTableIndex = args.buffer.getShort(
  209. args.offset + getFormat().OFFSET_COLUMN_VARIABLE_TABLE_INDEX);
  210. _fixedDataOffset = 0;
  211. } else {
  212. _fixedDataOffset = args.buffer.getShort(
  213. args.offset + getFormat().OFFSET_COLUMN_FIXED_DATA_OFFSET);
  214. _varLenTableIndex = 0;
  215. }
  216. }
  217. /**
  218. * Creates the appropriate ColumnImpl class and reads a column definition in
  219. * from a buffer
  220. * @param table owning table
  221. * @param buffer Buffer containing column definition
  222. * @param offset Offset in the buffer at which the column definition starts
  223. * @usage _advanced_method_
  224. */
  225. public static ColumnImpl create(TableImpl table, ByteBuffer buffer,
  226. int offset, String name, int displayIndex)
  227. throws IOException
  228. {
  229. InitArgs args = new InitArgs(table, buffer, offset, name, displayIndex);
  230. boolean calculated = ((args.extFlags & CALCULATED_EXT_FLAG_MASK) != 0);
  231. byte colType = args.colType;
  232. if(calculated) {
  233. // "real" data type is in the "result type" property
  234. PropertyMap colProps = table.getPropertyMaps().get(name);
  235. Byte resultType = (Byte)colProps.getValue(PropertyMap.RESULT_TYPE_PROP);
  236. if(resultType != null) {
  237. colType = resultType;
  238. }
  239. }
  240. try {
  241. args.type = DataType.fromByte(colType);
  242. } catch(IOException e) {
  243. LOG.warn(withErrorContext("Unsupported column type " + colType,
  244. table.getDatabase(), table.getName(), name));
  245. boolean variableLength = ((args.flags & FIXED_LEN_FLAG_MASK) == 0);
  246. args.type = (variableLength ? DataType.UNSUPPORTED_VARLEN :
  247. DataType.UNSUPPORTED_FIXEDLEN);
  248. return new UnsupportedColumnImpl(args);
  249. }
  250. if(calculated) {
  251. return CalculatedColumnUtil.create(args);
  252. }
  253. switch(args.type) {
  254. case TEXT:
  255. return new TextColumnImpl(args);
  256. case MEMO:
  257. return new MemoColumnImpl(args);
  258. case COMPLEX_TYPE:
  259. return new ComplexColumnImpl(args);
  260. default:
  261. // fall through
  262. }
  263. if(args.type.getHasScalePrecision()) {
  264. return new NumericColumnImpl(args);
  265. }
  266. if(args.type.isLongValue()) {
  267. return new LongValueColumnImpl(args);
  268. }
  269. return new ColumnImpl(args);
  270. }
  271. /**
  272. * Sets the usage maps for this column.
  273. */
  274. void setUsageMaps(UsageMap ownedPages, UsageMap freeSpacePages) {
  275. // base does nothing
  276. }
  277. void collectUsageMapPages(Collection<Integer> pages) {
  278. // base does nothing
  279. }
  280. /**
  281. * Secondary column initialization after the table is fully loaded.
  282. */
  283. void postTableLoadInit() throws IOException {
  284. // base does nothing
  285. }
  286. public TableImpl getTable() {
  287. return _table;
  288. }
  289. public DatabaseImpl getDatabase() {
  290. return getTable().getDatabase();
  291. }
  292. /**
  293. * @usage _advanced_method_
  294. */
  295. public JetFormat getFormat() {
  296. return getDatabase().getFormat();
  297. }
  298. /**
  299. * @usage _advanced_method_
  300. */
  301. public PageChannel getPageChannel() {
  302. return getDatabase().getPageChannel();
  303. }
  304. public String getName() {
  305. return _name;
  306. }
  307. public boolean isVariableLength() {
  308. return _variableLength;
  309. }
  310. public boolean isAutoNumber() {
  311. return _autoNumber;
  312. }
  313. /**
  314. * @usage _advanced_method_
  315. */
  316. public short getColumnNumber() {
  317. return _columnNumber;
  318. }
  319. public int getColumnIndex() {
  320. return _columnIndex;
  321. }
  322. /**
  323. * @usage _advanced_method_
  324. */
  325. public void setColumnIndex(int newColumnIndex) {
  326. _columnIndex = newColumnIndex;
  327. }
  328. /**
  329. * @usage _advanced_method_
  330. */
  331. public int getDisplayIndex() {
  332. return _displayIndex;
  333. }
  334. public DataType getType() {
  335. return _type;
  336. }
  337. public int getSQLType() throws SQLException {
  338. return _type.getSQLType();
  339. }
  340. public boolean isCompressedUnicode() {
  341. return false;
  342. }
  343. public byte getPrecision() {
  344. return (byte)getType().getDefaultPrecision();
  345. }
  346. public byte getScale() {
  347. return (byte)getType().getDefaultScale();
  348. }
  349. /**
  350. * @usage _intermediate_method_
  351. */
  352. public SortOrder getTextSortOrder() {
  353. return null;
  354. }
  355. /**
  356. * @usage _intermediate_method_
  357. */
  358. public short getTextCodePage() {
  359. return 0;
  360. }
  361. public short getLength() {
  362. return _columnLength;
  363. }
  364. public short getLengthInUnits() {
  365. return (short)getType().toUnitSize(getLength());
  366. }
  367. public boolean isCalculated() {
  368. return _calculated;
  369. }
  370. /**
  371. * @usage _advanced_method_
  372. */
  373. public int getVarLenTableIndex() {
  374. return _varLenTableIndex;
  375. }
  376. /**
  377. * @usage _advanced_method_
  378. */
  379. public int getFixedDataOffset() {
  380. return _fixedDataOffset;
  381. }
  382. protected Charset getCharset() {
  383. return getDatabase().getCharset();
  384. }
  385. protected Calendar getCalendar() {
  386. return getDatabase().getCalendar();
  387. }
  388. public boolean isAppendOnly() {
  389. return (getVersionHistoryColumn() != null);
  390. }
  391. public ColumnImpl getVersionHistoryColumn() {
  392. return null;
  393. }
  394. /**
  395. * Returns the number of database pages owned by this column.
  396. * @usage _intermediate_method_
  397. */
  398. public int getOwnedPageCount() {
  399. return 0;
  400. }
  401. /**
  402. * @usage _advanced_method_
  403. */
  404. public void setVersionHistoryColumn(ColumnImpl versionHistoryCol) {
  405. throw new UnsupportedOperationException();
  406. }
  407. public boolean isHyperlink() {
  408. return false;
  409. }
  410. public ComplexColumnInfo<? extends ComplexValue> getComplexInfo() {
  411. return null;
  412. }
  413. public ColumnValidator getColumnValidator() {
  414. return _validator;
  415. }
  416. public void setColumnValidator(ColumnValidator newValidator) {
  417. if(isAutoNumber()) {
  418. // cannot set autonumber validator (autonumber values are controlled
  419. // internally)
  420. if(newValidator != null) {
  421. throw new IllegalArgumentException(withErrorContext(
  422. "Cannot set ColumnValidator for autonumber columns"));
  423. }
  424. // just leave default validator instance alone
  425. return;
  426. }
  427. if(newValidator == null) {
  428. newValidator = getDatabase().getColumnValidatorFactory()
  429. .createValidator(this);
  430. if(newValidator == null) {
  431. newValidator = SimpleColumnValidator.INSTANCE;
  432. }
  433. }
  434. _validator = newValidator;
  435. }
  436. byte getOriginalDataType() {
  437. return _type.getValue();
  438. }
  439. private AutoNumberGenerator createAutoNumberGenerator() {
  440. if(!_autoNumber || (_type == null)) {
  441. return null;
  442. }
  443. switch(_type) {
  444. case LONG:
  445. return new LongAutoNumberGenerator();
  446. case GUID:
  447. return new GuidAutoNumberGenerator();
  448. case COMPLEX_TYPE:
  449. return new ComplexTypeAutoNumberGenerator();
  450. default:
  451. LOG.warn(withErrorContext("Unknown auto number column type " + _type));
  452. return new UnsupportedAutoNumberGenerator(_type);
  453. }
  454. }
  455. /**
  456. * Returns the AutoNumberGenerator for this column if this is an autonumber
  457. * column, {@code null} otherwise.
  458. * @usage _advanced_method_
  459. */
  460. public AutoNumberGenerator getAutoNumberGenerator() {
  461. return _autoNumberGenerator;
  462. }
  463. public PropertyMap getProperties() throws IOException {
  464. if(_props == null) {
  465. _props = getTable().getPropertyMaps().get(getName());
  466. }
  467. return _props;
  468. }
  469. public Object setRowValue(Object[] rowArray, Object value) {
  470. rowArray[_columnIndex] = value;
  471. return value;
  472. }
  473. public Object setRowValue(Map<String,Object> rowMap, Object value) {
  474. rowMap.put(_name, value);
  475. return value;
  476. }
  477. public Object getRowValue(Object[] rowArray) {
  478. return rowArray[_columnIndex];
  479. }
  480. public Object getRowValue(Map<String,?> rowMap) {
  481. return rowMap.get(_name);
  482. }
  483. public boolean storeInNullMask() {
  484. return (getType() == DataType.BOOLEAN);
  485. }
  486. public boolean writeToNullMask(Object value) {
  487. return toBooleanValue(value);
  488. }
  489. public Object readFromNullMask(boolean isNull) {
  490. return Boolean.valueOf(!isNull);
  491. }
  492. /**
  493. * Deserialize a raw byte value for this column into an Object
  494. * @param data The raw byte value
  495. * @return The deserialized Object
  496. * @usage _advanced_method_
  497. */
  498. public Object read(byte[] data) throws IOException {
  499. return read(data, PageChannel.DEFAULT_BYTE_ORDER);
  500. }
  501. /**
  502. * Deserialize a raw byte value for this column into an Object
  503. * @param data The raw byte value
  504. * @param order Byte order in which the raw value is stored
  505. * @return The deserialized Object
  506. * @usage _advanced_method_
  507. */
  508. public Object read(byte[] data, ByteOrder order) throws IOException {
  509. ByteBuffer buffer = ByteBuffer.wrap(data).order(order);
  510. switch(getType()) {
  511. case BOOLEAN:
  512. throw new IOException(withErrorContext("Tried to read a boolean from data instead of null mask."));
  513. case BYTE:
  514. return Byte.valueOf(buffer.get());
  515. case INT:
  516. return Short.valueOf(buffer.getShort());
  517. case LONG:
  518. return Integer.valueOf(buffer.getInt());
  519. case DOUBLE:
  520. return Double.valueOf(buffer.getDouble());
  521. case FLOAT:
  522. return Float.valueOf(buffer.getFloat());
  523. case SHORT_DATE_TIME:
  524. return readDateValue(buffer);
  525. case BINARY:
  526. return data;
  527. case TEXT:
  528. return decodeTextValue(data);
  529. case MONEY:
  530. return readCurrencyValue(buffer);
  531. case NUMERIC:
  532. return readNumericValue(buffer);
  533. case GUID:
  534. return readGUIDValue(buffer, order);
  535. case UNKNOWN_0D:
  536. case UNKNOWN_11:
  537. // treat like "binary" data
  538. return data;
  539. case COMPLEX_TYPE:
  540. return new ComplexValueForeignKeyImpl(this, buffer.getInt());
  541. case BIG_INT:
  542. return Long.valueOf(buffer.getLong());
  543. default:
  544. throw new IOException(withErrorContext("Unrecognized data type: " + _type));
  545. }
  546. }
  547. /**
  548. * Decodes "Currency" values.
  549. *
  550. * @param buffer Column value that points to currency data
  551. * @return BigDecimal representing the monetary value
  552. * @throws IOException if the value cannot be parsed
  553. */
  554. private BigDecimal readCurrencyValue(ByteBuffer buffer)
  555. throws IOException
  556. {
  557. if(buffer.remaining() != 8) {
  558. throw new IOException(withErrorContext("Invalid money value"));
  559. }
  560. return new BigDecimal(BigInteger.valueOf(buffer.getLong(0)), 4);
  561. }
  562. /**
  563. * Writes "Currency" values.
  564. */
  565. private void writeCurrencyValue(ByteBuffer buffer, Object value)
  566. throws IOException
  567. {
  568. Object inValue = value;
  569. try {
  570. BigDecimal decVal = toBigDecimal(value);
  571. inValue = decVal;
  572. // adjust scale (will cause the an ArithmeticException if number has too
  573. // many decimal places)
  574. decVal = decVal.setScale(4);
  575. // now, remove scale and convert to long (this will throw if the value is
  576. // too big)
  577. buffer.putLong(decVal.movePointRight(4).longValueExact());
  578. } catch(ArithmeticException e) {
  579. throw (IOException)
  580. new IOException(withErrorContext(
  581. "Currency value '" + inValue + "' out of range"))
  582. .initCause(e);
  583. }
  584. }
  585. /**
  586. * Decodes a NUMERIC field.
  587. */
  588. private BigDecimal readNumericValue(ByteBuffer buffer)
  589. {
  590. boolean negate = (buffer.get() != 0);
  591. byte[] tmpArr = ByteUtil.getBytes(buffer, 16);
  592. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  593. fixNumericByteOrder(tmpArr);
  594. }
  595. return toBigDecimal(tmpArr, negate, getScale());
  596. }
  597. static BigDecimal toBigDecimal(byte[] bytes, boolean negate, int scale)
  598. {
  599. if((bytes[0] & 0x80) != 0) {
  600. // the data is effectively unsigned, but the BigInteger handles it as
  601. // signed twos complement. we need to add an extra byte to the input so
  602. // that it will be treated as unsigned
  603. bytes = ByteUtil.copyOf(bytes, 0, bytes.length + 1, 1);
  604. }
  605. BigInteger intVal = new BigInteger(bytes);
  606. if(negate) {
  607. intVal = intVal.negate();
  608. }
  609. return new BigDecimal(intVal, scale);
  610. }
  611. /**
  612. * Writes a numeric value.
  613. */
  614. private void writeNumericValue(ByteBuffer buffer, Object value)
  615. throws IOException
  616. {
  617. Object inValue = value;
  618. try {
  619. BigDecimal decVal = toBigDecimal(value);
  620. inValue = decVal;
  621. int signum = decVal.signum();
  622. if(signum < 0) {
  623. decVal = decVal.negate();
  624. }
  625. // write sign byte
  626. buffer.put((signum < 0) ? NUMERIC_NEGATIVE_BYTE : 0);
  627. // adjust scale according to this column type (will cause the an
  628. // ArithmeticException if number has too many decimal places)
  629. decVal = decVal.setScale(getScale());
  630. // check precision
  631. if(decVal.precision() > getPrecision()) {
  632. throw new IOException(withErrorContext(
  633. "Numeric value is too big for specified precision "
  634. + getPrecision() + ": " + decVal));
  635. }
  636. // convert to unscaled BigInteger, big-endian bytes
  637. byte[] intValBytes = toUnscaledByteArray(
  638. decVal, getType().getFixedSize() - 1);
  639. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  640. fixNumericByteOrder(intValBytes);
  641. }
  642. buffer.put(intValBytes);
  643. } catch(ArithmeticException e) {
  644. throw (IOException)
  645. new IOException(withErrorContext(
  646. "Numeric value '" + inValue + "' out of range"))
  647. .initCause(e);
  648. }
  649. }
  650. byte[] toUnscaledByteArray(BigDecimal decVal, int maxByteLen)
  651. throws IOException
  652. {
  653. // convert to unscaled BigInteger, big-endian bytes
  654. byte[] intValBytes = decVal.unscaledValue().toByteArray();
  655. if(intValBytes.length > maxByteLen) {
  656. if((intValBytes[0] == 0) && ((intValBytes.length - 1) == maxByteLen)) {
  657. // in order to not return a negative two's complement value,
  658. // toByteArray() may return an extra leading 0 byte. we are working
  659. // with unsigned values, so we can drop the extra leading 0
  660. intValBytes = ByteUtil.copyOf(intValBytes, 1, maxByteLen);
  661. } else {
  662. throw new IOException(withErrorContext(
  663. "Too many bytes for valid BigInteger?"));
  664. }
  665. } else if(intValBytes.length < maxByteLen) {
  666. intValBytes = ByteUtil.copyOf(intValBytes, 0, maxByteLen,
  667. (maxByteLen - intValBytes.length));
  668. }
  669. return intValBytes;
  670. }
  671. /**
  672. * Decodes a date value.
  673. */
  674. private Date readDateValue(ByteBuffer buffer)
  675. {
  676. // seems access stores dates in the local timezone. guess you just hope
  677. // you read it in the same timezone in which it was written!
  678. long dateBits = buffer.getLong();
  679. long time = fromDateDouble(Double.longBitsToDouble(dateBits));
  680. return new DateExt(time, dateBits);
  681. }
  682. /**
  683. * Returns a java long time value converted from an access date double.
  684. * @usage _advanced_method_
  685. */
  686. public long fromDateDouble(double value)
  687. {
  688. long localTime = fromLocalDateDouble(value);
  689. return localTime - getFromLocalTimeZoneOffset(localTime);
  690. }
  691. static long fromLocalDateDouble(double value)
  692. {
  693. long datePart = ((long)value) * MILLISECONDS_PER_DAY;
  694. // the fractional part of the double represents the time. it is always
  695. // a positive fraction of the day (even if the double is negative),
  696. // _not_ the time distance from zero (as one would expect with "normal"
  697. // numbers). therefore, we need to do a little number logic to convert
  698. // the absolute time fraction into a normal distance from zero number.
  699. long timePart = Math.round((Math.abs(value) % 1.0) *
  700. (double)MILLISECONDS_PER_DAY);
  701. long time = datePart + timePart;
  702. time -= MILLIS_BETWEEN_EPOCH_AND_1900;
  703. return time;
  704. }
  705. /**
  706. * Writes a date value.
  707. */
  708. private void writeDateValue(ByteBuffer buffer, Object value)
  709. {
  710. if(value == null) {
  711. buffer.putDouble(0d);
  712. } else if(value instanceof DateExt) {
  713. // this is a Date value previously read from readDateValue(). use the
  714. // original bits to store the value so we don't lose any precision
  715. buffer.putLong(((DateExt)value).getDateBits());
  716. } else {
  717. buffer.putDouble(toDateDouble(value));
  718. }
  719. }
  720. /**
  721. * Returns an access date double converted from a java Date/Calendar/Number
  722. * time value.
  723. * @usage _advanced_method_
  724. */
  725. public double toDateDouble(Object value)
  726. {
  727. // seems access stores dates in the local timezone. guess you just
  728. // hope you read it in the same timezone in which it was written!
  729. long time = toDateLong(value);
  730. time += getToLocalTimeZoneOffset(time);
  731. return toLocalDateDouble(time);
  732. }
  733. static double toLocalDateDouble(long time)
  734. {
  735. time += MILLIS_BETWEEN_EPOCH_AND_1900;
  736. if(time < 0L) {
  737. // reverse the crazy math described in fromLocalDateDouble
  738. long timePart = -time % MILLISECONDS_PER_DAY;
  739. if(timePart > 0) {
  740. time -= (2 * (MILLISECONDS_PER_DAY - timePart));
  741. }
  742. }
  743. return time / (double)MILLISECONDS_PER_DAY;
  744. }
  745. /**
  746. * @return an appropriate Date long value for the given object
  747. */
  748. private static long toDateLong(Object value)
  749. {
  750. return ((value instanceof Date) ?
  751. ((Date)value).getTime() :
  752. ((value instanceof Calendar) ?
  753. ((Calendar)value).getTimeInMillis() :
  754. ((Number)value).longValue()));
  755. }
  756. /**
  757. * Gets the timezone offset from UTC to local time for the given time
  758. * (including DST).
  759. */
  760. private long getToLocalTimeZoneOffset(long time)
  761. {
  762. Calendar c = getCalendar();
  763. c.setTimeInMillis(time);
  764. return ((long)c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET));
  765. }
  766. /**
  767. * Gets the timezone offset from local time to UTC for the given time
  768. * (including DST).
  769. */
  770. private long getFromLocalTimeZoneOffset(long time)
  771. {
  772. // getting from local time back to UTC is a little wonky (and not
  773. // guaranteed to get you back to where you started)
  774. Calendar c = getCalendar();
  775. c.setTimeInMillis(time);
  776. // apply the zone offset first to get us closer to the original time
  777. c.setTimeInMillis(time - c.get(Calendar.ZONE_OFFSET));
  778. return ((long)c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET));
  779. }
  780. /**
  781. * Decodes a GUID value.
  782. */
  783. private static String readGUIDValue(ByteBuffer buffer, ByteOrder order)
  784. {
  785. if(order != ByteOrder.BIG_ENDIAN) {
  786. byte[] tmpArr = ByteUtil.getBytes(buffer, 16);
  787. // the first 3 guid components are integer components which need to
  788. // respect endianness, so swap 4-byte int, 2-byte int, 2-byte int
  789. ByteUtil.swap4Bytes(tmpArr, 0);
  790. ByteUtil.swap2Bytes(tmpArr, 4);
  791. ByteUtil.swap2Bytes(tmpArr, 6);
  792. buffer = ByteBuffer.wrap(tmpArr);
  793. }
  794. StringBuilder sb = new StringBuilder(22);
  795. sb.append("{");
  796. sb.append(ByteUtil.toHexString(buffer, 0, 4,
  797. false));
  798. sb.append("-");
  799. sb.append(ByteUtil.toHexString(buffer, 4, 2,
  800. false));
  801. sb.append("-");
  802. sb.append(ByteUtil.toHexString(buffer, 6, 2,
  803. false));
  804. sb.append("-");
  805. sb.append(ByteUtil.toHexString(buffer, 8, 2,
  806. false));
  807. sb.append("-");
  808. sb.append(ByteUtil.toHexString(buffer, 10, 6,
  809. false));
  810. sb.append("}");
  811. return (sb.toString());
  812. }
  813. /**
  814. * Writes a GUID value.
  815. */
  816. private void writeGUIDValue(ByteBuffer buffer, Object value)
  817. throws IOException
  818. {
  819. Matcher m = GUID_PATTERN.matcher(toCharSequence(value));
  820. if(!m.matches()) {
  821. throw new IOException(withErrorContext("Invalid GUID: " + value));
  822. }
  823. ByteBuffer origBuffer = null;
  824. byte[] tmpBuf = null;
  825. if(buffer.order() != ByteOrder.BIG_ENDIAN) {
  826. // write to a temp buf so we can do some swapping below
  827. origBuffer = buffer;
  828. tmpBuf = new byte[16];
  829. buffer = ByteBuffer.wrap(tmpBuf);
  830. }
  831. ByteUtil.writeHexString(buffer, m.group(1));
  832. ByteUtil.writeHexString(buffer, m.group(2));
  833. ByteUtil.writeHexString(buffer, m.group(3));
  834. ByteUtil.writeHexString(buffer, m.group(4));
  835. ByteUtil.writeHexString(buffer, m.group(5));
  836. if(tmpBuf != null) {
  837. // the first 3 guid components are integer components which need to
  838. // respect endianness, so swap 4-byte int, 2-byte int, 2-byte int
  839. ByteUtil.swap4Bytes(tmpBuf, 0);
  840. ByteUtil.swap2Bytes(tmpBuf, 4);
  841. ByteUtil.swap2Bytes(tmpBuf, 6);
  842. origBuffer.put(tmpBuf);
  843. }
  844. }
  845. /**
  846. * Returns {@code true} if the given value is a "guid" value.
  847. */
  848. static boolean isGUIDValue(Object value) throws IOException {
  849. return GUID_PATTERN.matcher(toCharSequence(value)).matches();
  850. }
  851. /**
  852. * Passes the given obj through the currently configured validator for this
  853. * column and returns the result.
  854. */
  855. public Object validate(Object obj) throws IOException {
  856. return _validator.validate(this, obj);
  857. }
  858. /**
  859. * Serialize an Object into a raw byte value for this column in little
  860. * endian order
  861. * @param obj Object to serialize
  862. * @return A buffer containing the bytes
  863. * @usage _advanced_method_
  864. */
  865. public ByteBuffer write(Object obj, int remainingRowLength)
  866. throws IOException
  867. {
  868. return write(obj, remainingRowLength, PageChannel.DEFAULT_BYTE_ORDER);
  869. }
  870. /**
  871. * Serialize an Object into a raw byte value for this column
  872. * @param obj Object to serialize
  873. * @param order Order in which to serialize
  874. * @return A buffer containing the bytes
  875. * @usage _advanced_method_
  876. */
  877. public ByteBuffer write(Object obj, int remainingRowLength, ByteOrder order)
  878. throws IOException
  879. {
  880. if(isRawData(obj)) {
  881. // just slap it right in (not for the faint of heart!)
  882. return ByteBuffer.wrap(((RawData)obj).getBytes());
  883. }
  884. return writeRealData(obj, remainingRowLength, order);
  885. }
  886. protected ByteBuffer writeRealData(Object obj, int remainingRowLength,
  887. ByteOrder order)
  888. throws IOException
  889. {
  890. if(!isVariableLength() || !getType().isVariableLength()) {
  891. return writeFixedLengthField(obj, order);
  892. }
  893. // this is an "inline" var length field
  894. switch(getType()) {
  895. case NUMERIC:
  896. // don't ask me why numerics are "var length" columns...
  897. ByteBuffer buffer = PageChannel.createBuffer(
  898. getType().getFixedSize(), order);
  899. writeNumericValue(buffer, obj);
  900. buffer.flip();
  901. return buffer;
  902. case TEXT:
  903. return encodeTextValue(
  904. obj, 0, getLengthInUnits(), false).order(order);
  905. case BINARY:
  906. case UNKNOWN_0D:
  907. case UNSUPPORTED_VARLEN:
  908. // should already be "encoded"
  909. break;
  910. default:
  911. throw new RuntimeException(withErrorContext(
  912. "unexpected inline var length type: " + getType()));
  913. }
  914. ByteBuffer buffer = ByteBuffer.wrap(toByteArray(obj)).order(order);
  915. return buffer;
  916. }
  917. /**
  918. * Serialize an Object into a raw byte value for this column
  919. * @param obj Object to serialize
  920. * @param order Order in which to serialize
  921. * @return A buffer containing the bytes
  922. * @usage _advanced_method_
  923. */
  924. protected ByteBuffer writeFixedLengthField(Object obj, ByteOrder order)
  925. throws IOException
  926. {
  927. int size = getType().getFixedSize(_columnLength);
  928. ByteBuffer buffer = writeFixedLengthField(
  929. obj, PageChannel.createBuffer(size, order));
  930. buffer.flip();
  931. return buffer;
  932. }
  933. protected ByteBuffer writeFixedLengthField(Object obj, ByteBuffer buffer)
  934. throws IOException
  935. {
  936. // since booleans are not written by this method, it's safe to convert any
  937. // incoming boolean into an integer.
  938. obj = booleanToInteger(obj);
  939. switch(getType()) {
  940. case BOOLEAN:
  941. //Do nothing
  942. break;
  943. case BYTE:
  944. buffer.put(toNumber(obj).byteValue());
  945. break;
  946. case INT:
  947. buffer.putShort(toNumber(obj).shortValue());
  948. break;
  949. case LONG:
  950. buffer.putInt(toNumber(obj).intValue());
  951. break;
  952. case MONEY:
  953. writeCurrencyValue(buffer, obj);
  954. break;
  955. case FLOAT:
  956. buffer.putFloat(toNumber(obj).floatValue());
  957. break;
  958. case DOUBLE:
  959. buffer.putDouble(toNumber(obj).doubleValue());
  960. break;
  961. case SHORT_DATE_TIME:
  962. writeDateValue(buffer, obj);
  963. break;
  964. case TEXT:
  965. // apparently text numeric values are also occasionally written as fixed
  966. // length...
  967. int numChars = getLengthInUnits();
  968. // force uncompressed encoding for fixed length text
  969. buffer.put(encodeTextValue(obj, numChars, numChars, true));
  970. break;
  971. case GUID:
  972. writeGUIDValue(buffer, obj);
  973. break;
  974. case NUMERIC:
  975. // yes, that's right, occasionally numeric values are written as fixed
  976. // length...
  977. writeNumericValue(buffer, obj);
  978. break;
  979. case BINARY:
  980. case UNKNOWN_0D:
  981. case UNKNOWN_11:
  982. case COMPLEX_TYPE:
  983. buffer.putInt(toNumber(obj).intValue());
  984. break;
  985. case BIG_INT:
  986. buffer.putLong(toNumber(obj).longValue());
  987. break;
  988. case UNSUPPORTED_FIXEDLEN:
  989. byte[] bytes = toByteArray(obj);
  990. if(bytes.length != getLength()) {
  991. throw new IOException(withErrorContext(
  992. "Invalid fixed size binary data, size "
  993. + getLength() + ", got " + bytes.length));
  994. }
  995. buffer.put(bytes);
  996. break;
  997. default:
  998. throw new IOException(withErrorContext(
  999. "Unsupported data type: " + getType()));
  1000. }
  1001. return buffer;
  1002. }
  1003. /**
  1004. * Decodes a compressed or uncompressed text value.
  1005. */
  1006. String decodeTextValue(byte[] data)
  1007. throws IOException
  1008. {
  1009. // see if data is compressed. the 0xFF, 0xFE sequence indicates that
  1010. // compression is used (sort of, see algorithm below)
  1011. boolean isCompressed = ((data.length > 1) &&
  1012. (data[0] == TEXT_COMPRESSION_HEADER[0]) &&
  1013. (data[1] == TEXT_COMPRESSION_HEADER[1]));
  1014. if(isCompressed) {
  1015. // this is a whacky compression combo that switches back and forth
  1016. // between compressed/uncompressed using a 0x00 byte (starting in
  1017. // compressed mode)
  1018. StringBuilder textBuf = new StringBuilder(data.length);
  1019. // start after two bytes indicating compression use
  1020. int dataStart = TEXT_COMPRESSION_HEADER.length;
  1021. int dataEnd = dataStart;
  1022. boolean inCompressedMode = true;
  1023. while(dataEnd < data.length) {
  1024. if(data[dataEnd] == (byte)0x00) {
  1025. // handle current segment
  1026. decodeTextSegment(data, dataStart, dataEnd, inCompressedMode,
  1027. textBuf);
  1028. inCompressedMode = !inCompressedMode;
  1029. ++dataEnd;
  1030. dataStart = dataEnd;
  1031. } else {
  1032. ++dataEnd;
  1033. }
  1034. }
  1035. // handle last segment
  1036. decodeTextSegment(data, dataStart, dataEnd, inCompressedMode, textBuf);
  1037. return textBuf.toString();
  1038. }
  1039. return decodeUncompressedText(data, getCharset());
  1040. }
  1041. /**
  1042. * Decodes a segnment of a text value into the given buffer according to the
  1043. * given status of the segment (compressed/uncompressed).
  1044. */
  1045. private void decodeTextSegment(byte[] data, int dataStart, int dataEnd,
  1046. boolean inCompressedMode,
  1047. StringBuilder textBuf)
  1048. {
  1049. if(dataEnd <= dataStart) {
  1050. // no data
  1051. return;
  1052. }
  1053. int dataLength = dataEnd - dataStart;
  1054. if(inCompressedMode) {
  1055. byte[] tmpData = new byte[dataLength * 2];
  1056. int tmpIdx = 0;
  1057. for(int i = dataStart; i < dataEnd; ++i) {
  1058. tmpData[tmpIdx] = data[i];
  1059. tmpIdx += 2;
  1060. }
  1061. data = tmpData;
  1062. dataStart = 0;
  1063. dataLength = data.length;
  1064. }
  1065. textBuf.append(decodeUncompressedText(data, dataStart, dataLength,
  1066. getCharset()));
  1067. }
  1068. /**
  1069. * @param textBytes bytes of text to decode
  1070. * @return the decoded string
  1071. */
  1072. private static CharBuffer decodeUncompressedText(
  1073. byte[] textBytes, int startPos, int length, Charset charset)
  1074. {
  1075. return charset.decode(ByteBuffer.wrap(textBytes, startPos, length));
  1076. }
  1077. /**
  1078. * Encodes a text value, possibly compressing.
  1079. */
  1080. ByteBuffer encodeTextValue(Object obj, int minChars, int maxChars,
  1081. boolean forceUncompressed)
  1082. throws IOException
  1083. {
  1084. CharSequence text = toCharSequence(obj);
  1085. if((text.length() > maxChars) || (text.length() < minChars)) {
  1086. throw new IOException(withErrorContext(
  1087. "Text is wrong length for " + getType() +
  1088. " column, max " + maxChars
  1089. + ", min " + minChars + ", got " + text.length()));
  1090. }
  1091. // may only compress if column type allows it
  1092. if(!forceUncompressed && isCompressedUnicode() &&
  1093. (text.length() <= getFormat().MAX_COMPRESSED_UNICODE_SIZE) &&
  1094. isUnicodeCompressible(text)) {
  1095. byte[] encodedChars = new byte[TEXT_COMPRESSION_HEADER.length +
  1096. text.length()];
  1097. encodedChars[0] = TEXT_COMPRESSION_HEADER[0];
  1098. encodedChars[1] = TEXT_COMPRESSION_HEADER[1];
  1099. for(int i = 0; i < text.length(); ++i) {
  1100. encodedChars[i + TEXT_COMPRESSION_HEADER.length] =
  1101. (byte)text.charAt(i);
  1102. }
  1103. return ByteBuffer.wrap(encodedChars);
  1104. }
  1105. return encodeUncompressedText(text, getCharset());
  1106. }
  1107. /**
  1108. * Returns {@code true} if the given text can be compressed using compressed
  1109. * unicode, {@code false} otherwise.
  1110. */
  1111. private static boolean isUnicodeCompressible(CharSequence text) {
  1112. // only attempt to compress > 2 chars (compressing less than 3 chars would
  1113. // not result in a space savings due to the 2 byte compression header)
  1114. if(text.length() <= TEXT_COMPRESSION_HEADER.length) {
  1115. return false;
  1116. }
  1117. // now, see if it is all compressible characters
  1118. for(int i = 0; i < text.length(); ++i) {
  1119. char c = text.charAt(i);
  1120. if((c < MIN_COMPRESS_CHAR) || (c > MAX_COMPRESS_CHAR)) {
  1121. return false;
  1122. }
  1123. }
  1124. return true;
  1125. }
  1126. /**
  1127. * Constructs a byte containing the flags for this column.
  1128. */
  1129. private static byte getColumnBitFlags(ColumnBuilder col) {
  1130. byte flags = UPDATABLE_FLAG_MASK;
  1131. if(!col.isVariableLength()) {
  1132. flags |= FIXED_LEN_FLAG_MASK;
  1133. }
  1134. if(col.isAutoNumber()) {
  1135. byte autoNumFlags = 0;
  1136. switch(col.getType()) {
  1137. case LONG:
  1138. case COMPLEX_TYPE:
  1139. autoNumFlags = AUTO_NUMBER_FLAG_MASK;
  1140. break;
  1141. case GUID:
  1142. autoNumFlags = AUTO_NUMBER_GUID_FLAG_MASK;
  1143. break;
  1144. default:
  1145. // unknown autonum type
  1146. }
  1147. flags |= autoNumFlags;
  1148. }
  1149. if(col.isHyperlink()) {
  1150. flags |= HYPERLINK_FLAG_MASK;
  1151. }
  1152. return flags;
  1153. }
  1154. @Override
  1155. public String toString() {
  1156. ToStringBuilder sb = CustomToStringStyle.builder(this)
  1157. .append("name", "(" + _table.getName() + ") " + _name);
  1158. byte typeValue = getOriginalDataType();
  1159. sb.append("type", "0x" + Integer.toHexString(typeValue) +
  1160. " (" + _type + ")")
  1161. .append("number", _columnNumber)
  1162. .append("length", _columnLength)
  1163. .append("variableLength", _variableLength);
  1164. if(_calculated) {
  1165. sb.append("calculated", _calculated);
  1166. }
  1167. if(_type.isTextual()) {
  1168. sb.append("compressedUnicode", isCompressedUnicode())
  1169. .append("textSortOrder", getTextSortOrder());
  1170. if(getTextCodePage() > 0) {
  1171. sb.append("textCodePage", getTextCodePage());
  1172. }
  1173. if(isAppendOnly()) {
  1174. sb.append("appendOnly", isAppendOnly());
  1175. }
  1176. if(isHyperlink()) {
  1177. sb.append("hyperlink", isHyperlink());
  1178. }
  1179. }
  1180. if(_type.getHasScalePrecision()) {
  1181. sb.append("precision", getPrecision())
  1182. .append("scale", getScale());
  1183. }
  1184. if(_autoNumber) {
  1185. sb.append("lastAutoNumber", _autoNumberGenerator.getLast());
  1186. }
  1187. if(getComplexInfo() != null) {
  1188. sb.append("complexInfo", getComplexInfo());
  1189. }
  1190. return sb.toString();
  1191. }
  1192. /**
  1193. * @param textBytes bytes of text to decode
  1194. * @param charset relevant charset
  1195. * @return the decoded string
  1196. * @usage _advanced_method_
  1197. */
  1198. public static String decodeUncompressedText(byte[] textBytes,
  1199. Charset charset)
  1200. {
  1201. return decodeUncompressedText(textBytes, 0, textBytes.length, charset)
  1202. .toString();
  1203. }
  1204. /**
  1205. * @param text Text to encode
  1206. * @param charset database charset
  1207. * @return A buffer with the text encoded
  1208. * @usage _advanced_method_
  1209. */
  1210. public static ByteBuffer encodeUncompressedText(CharSequence text,
  1211. Charset charset)
  1212. {
  1213. CharBuffer cb = ((text instanceof CharBuffer) ?
  1214. (CharBuffer)text : CharBuffer.wrap(text));
  1215. return charset.encode(cb);
  1216. }
  1217. /**
  1218. * Orders Columns by column number.
  1219. * @usage _general_method_
  1220. */
  1221. public int compareTo(ColumnImpl other) {
  1222. if (_columnNumber > other.getColumnNumber()) {
  1223. return 1;
  1224. } else if (_columnNumber < other.getColumnNumber()) {
  1225. return -1;
  1226. } else {
  1227. return 0;
  1228. }
  1229. }
  1230. /**
  1231. * @param columns A list of columns in a table definition
  1232. * @return The number of variable length columns found in the list
  1233. * @usage _advanced_method_
  1234. */
  1235. public static short countVariableLength(List<ColumnBuilder> columns) {
  1236. short rtn = 0;
  1237. for (ColumnBuilder col : columns) {
  1238. if (col.isVariableLength()) {
  1239. rtn++;
  1240. }
  1241. }
  1242. return rtn;
  1243. }
  1244. /**
  1245. * @return an appropriate BigDecimal representation of the given object.
  1246. * <code>null</code> is returned as 0 and Numbers are converted
  1247. * using their double representation.
  1248. */
  1249. static BigDecimal toBigDecimal(Object value)
  1250. {
  1251. if(value == null) {
  1252. return BigDecimal.ZERO;
  1253. } else if(value instanceof BigDecimal) {
  1254. return (BigDecimal)value;
  1255. } else if(value instanceof BigInteger) {
  1256. return new BigDecimal((BigInteger)value);
  1257. } else if(value instanceof Number) {
  1258. return new BigDecimal(((Number)value).doubleValue());
  1259. }
  1260. return new BigDecimal(value.toString());
  1261. }
  1262. /**
  1263. * @return an appropriate Number representation of the given object.
  1264. * <code>null</code> is returned as 0 and Strings are parsed as
  1265. * Doubles.
  1266. */
  1267. private static Number toNumber(Object value)
  1268. {
  1269. if(value == null) {
  1270. return BigDecimal.ZERO;
  1271. } else if(value instanceof Number) {
  1272. return (Number)value;
  1273. }
  1274. return Double.valueOf(value.toString());
  1275. }
  1276. /**
  1277. * @return an appropriate CharSequence representation of the given object.
  1278. * @usage _advanced_method_
  1279. */
  1280. public static CharSequence toCharSequence(Object value)
  1281. throws IOException
  1282. {
  1283. if(value == null) {
  1284. return null;
  1285. } else if(value instanceof CharSequence) {
  1286. return (CharSequence)value;
  1287. } else if(value instanceof Clob) {
  1288. try {
  1289. Clob c = (Clob)value;
  1290. // note, start pos is 1-based
  1291. return c.getSubString(1L, (int)c.length());
  1292. } catch(SQLException e) {
  1293. throw (IOException)(new IOException(e.getMessage())).initCause(e);
  1294. }
  1295. } else if(value instanceof Reader) {
  1296. char[] buf = new char[8 * 1024];
  1297. StringBuilder sout = new StringBuilder();
  1298. Reader in = (Reader)value;
  1299. int read = 0;
  1300. while((read = in.read(buf)) != -1) {
  1301. sout.append(buf, 0, read);
  1302. }
  1303. return sout;
  1304. }
  1305. return value.toString();
  1306. }
  1307. /**
  1308. * @return an appropriate byte[] representation of the given object.
  1309. * @usage _advanced_method_
  1310. */
  1311. public static byte[] toByteArray(Object value)
  1312. throws IOException
  1313. {
  1314. if(value == null) {
  1315. return null;
  1316. } else if(value instanceof byte[]) {
  1317. return (byte[])value;
  1318. } else if(value instanceof OleUtil.OleBlobImpl) {
  1319. return ((OleUtil.OleBlobImpl)value).getBytes();
  1320. } else if(value instanceof Blob) {
  1321. try {
  1322. Blob b = (Blob)value;
  1323. // note, start pos is 1-based
  1324. return b.getBytes(1L, (int)b.length());
  1325. } catch(SQLException e) {
  1326. throw (IOException)(new IOException(e.getMessage())).initCause(e);
  1327. }
  1328. } else if(value instanceof RawData) {
  1329. return ((RawData)value).getBytes();
  1330. }
  1331. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  1332. if(value instanceof InputStream) {
  1333. ByteUtil.copy((InputStream)value, bout);
  1334. } else {
  1335. // if all else fails, serialize it
  1336. ObjectOutputStream oos = new ObjectOutputStream(bout);
  1337. oos.writeObject(value);
  1338. oos.close();
  1339. }
  1340. return bout.toByteArray();
  1341. }
  1342. /**
  1343. * Interpret a boolean value (null == false)
  1344. * @usage _advanced_method_
  1345. */
  1346. public static boolean toBooleanValue(Object obj) {
  1347. if(obj == null) {
  1348. return false;
  1349. } else if(obj instanceof Boolean) {
  1350. return ((Boolean)obj).booleanValue();
  1351. }
  1352. return Boolean.parseBoolean(obj.toString());
  1353. }
  1354. /**
  1355. * Swaps the bytes of the given numeric in place.
  1356. */
  1357. private static void fixNumericByteOrder(byte[] bytes)
  1358. {
  1359. // fix endianness of each 4 byte segment
  1360. for(int i = 0; i < bytes.length; i+=4) {
  1361. ByteUtil.swap4Bytes(bytes, i);
  1362. }
  1363. }
  1364. /**
  1365. * Treat booleans as integers (C-style).
  1366. */
  1367. protected static Object booleanToInteger(Object obj) {
  1368. if (obj instanceof Boolean) {
  1369. obj = ((Boolean) obj) ? 1 : 0;
  1370. }
  1371. return obj;
  1372. }
  1373. /**
  1374. * Returns a wrapper for raw column data that can be written without
  1375. * understanding the data. Useful for wrapping unparseable data for
  1376. * re-writing.
  1377. */
  1378. public static RawData rawDataWrapper(byte[] bytes) {
  1379. return new RawData(bytes);
  1380. }
  1381. /**
  1382. * Returns {@code true} if the given value is "raw" column data,
  1383. * {@code false} otherwise.
  1384. * @usage _advanced_method_
  1385. */
  1386. public static boolean isRawData(Object value) {
  1387. return(value instanceof RawData);
  1388. }
  1389. /**
  1390. * Writes the column definitions into a table definition buffer.
  1391. * @param buffer Buffer to write to
  1392. */
  1393. protected static void writeDefinitions(TableCreator creator, ByteBuffer buffer)
  1394. throws IOException
  1395. {
  1396. // we specifically put the "long variable" values after the normal
  1397. // variable length values so that we have a better chance of fitting it
  1398. // all (because "long variable" values can go in separate pages)
  1399. int longVariableOffset = creator.countNonLongVariableLength();
  1400. creator.setColumnOffsets(0, 0, longVariableOffset);
  1401. for (ColumnBuilder col : creator.getColumns()) {
  1402. writeDefinition(creator, col, buffer);
  1403. }
  1404. for (ColumnBuilder col : creator.getColumns()) {
  1405. TableImpl.writeName(buffer, col.getName(), creator.getCharset());
  1406. }
  1407. }
  1408. protected static void writeDefinition(
  1409. TableMutator mutator, ColumnBuilder col, ByteBuffer buffer)
  1410. throws IOException
  1411. {
  1412. TableMutator.ColumnOffsets colOffsets = mutator.getColumnOffsets();
  1413. buffer.put(col.getType().getValue());
  1414. buffer.putInt(TableImpl.MAGIC_TABLE_NUMBER); //constant magic number
  1415. buffer.putShort(col.getColumnNumber()); //Column Number
  1416. if(col.isVariableLength()) {
  1417. buffer.putShort(colOffsets.getNextVariableOffset(col));
  1418. } else {
  1419. buffer.putShort((short) 0);
  1420. }
  1421. buffer.putShort(col.getColumnNumber()); //Column Number again
  1422. if(col.getType().isTextual()) {
  1423. // this will write 4 bytes (note we don't support writing dbs which
  1424. // use the text code page)
  1425. writeSortOrder(buffer, col.getTextSortOrder(), mutator.getFormat());
  1426. } else {
  1427. // note scale/precision not stored for calculated numeric fields
  1428. if(col.getType().getHasScalePrecision() && !col.isCalculated()) {
  1429. buffer.put(col.getPrecision()); // numeric precision
  1430. buffer.put(col.getScale()); // numeric scale
  1431. } else {
  1432. buffer.put((byte) 0x00); //unused
  1433. buffer.put((byte) 0x00); //unused
  1434. }
  1435. buffer.putShort((short) 0); //Unknown
  1436. }
  1437. buffer.put(getColumnBitFlags(col)); // misc col flags
  1438. // note access doesn't seem to allow unicode compression for calced fields
  1439. if(col.isCalculated()) {
  1440. buffer.put(CALCULATED_EXT_FLAG_MASK);
  1441. } else if (col.isCompressedUnicode()) { //Compressed
  1442. buffer.put(COMPRESSED_UNICODE_EXT_FLAG_MASK);
  1443. } else {
  1444. buffer.put((byte)0);
  1445. }
  1446. buffer.putInt(0); //Unknown, but always 0.
  1447. //Offset for fixed length columns
  1448. if(col.isVariableLength()) {
  1449. buffer.putShort((short) 0);
  1450. } else {
  1451. buffer.putShort(colOffsets.getNextFixedOffset(col));
  1452. }
  1453. if(!col.getType().isLongValue()) {
  1454. short length = col.getLength();
  1455. if(col.isCalculated()) {
  1456. // calced columns have additional value overhead
  1457. if(!col.getType().isVariableLength() ||
  1458. col.getType().getHasScalePrecision()) {
  1459. length = CalculatedColumnUtil.CALC_FIXED_FIELD_LEN;
  1460. } else {
  1461. length += CalculatedColumnUtil.CALC_EXTRA_DATA_LEN;
  1462. }
  1463. }
  1464. buffer.putShort(length); //Column length
  1465. } else {
  1466. buffer.putShort((short)0x0000); // unused
  1467. }
  1468. }
  1469. protected static void writeColUsageMapDefinitions(
  1470. TableCreator creator, ByteBuffer buffer)
  1471. throws IOException
  1472. {
  1473. // write long value column usage map references
  1474. for(ColumnBuilder lvalCol : creator.getLongValueColumns()) {
  1475. writeColUsageMapDefinition(creator, lvalCol, buffer);
  1476. }
  1477. }
  1478. protected static void writeColUsageMapDefinition(
  1479. TableMutator creator, ColumnBuilder lvalCol, ByteBuffer buffer)
  1480. throws IOException
  1481. {
  1482. TableMutator.ColumnState colState = creator.getColumnState(lvalCol);
  1483. buffer.putShort(lvalCol.getColumnNumber());
  1484. // owned pages umap (both are on same page)
  1485. buffer.put(colState.getUmapOwnedRowNumber());
  1486. ByteUtil.put3ByteInt(buffer, colState.getUmapPageNumber());
  1487. // free space pages umap
  1488. buffer.put(colState.getUmapFreeRowNumber());
  1489. ByteUtil.put3ByteInt(buffer, colState.getUmapPageNumber());
  1490. }
  1491. /**
  1492. * Reads the sort order info from the given buffer from the given position.
  1493. */
  1494. static SortOrder readSortOrder(ByteBuffer buffer, int position,
  1495. JetFormat format)
  1496. {
  1497. short value = buffer.getShort(position);
  1498. byte version = 0;
  1499. if(format.SIZE_SORT_ORDER == 4) {
  1500. version = buffer.get(position + 3);
  1501. }
  1502. if(value == 0) {
  1503. // probably a file we wrote, before handling sort order
  1504. return format.DEFAULT_SORT_ORDER;
  1505. }
  1506. if(value == GENERAL_SORT_ORDER_VALUE) {
  1507. if(version == GENERAL_LEGACY_SORT_ORDER.getVersion()) {
  1508. return GENERAL_LEGACY_SORT_ORDER;
  1509. }
  1510. if(version == GENERAL_SORT_ORDER.getVersion()) {
  1511. return GENERAL_SORT_ORDER;
  1512. }
  1513. }
  1514. return new SortOrder(value, version);
  1515. }
  1516. /**
  1517. * Reads the column cade page info from the given buffer, if supported for
  1518. * this db.
  1519. */
  1520. static short readCodePage(ByteBuffer buffer, int offset, JetFormat format)
  1521. {
  1522. int cpOffset = format.OFFSET_COLUMN_CODE_PAGE;
  1523. return ((cpOffset >= 0) ? buffer.getShort(offset + cpOffset) : 0);
  1524. }
  1525. /**
  1526. * Read the extra flags field for a column definition.
  1527. */
  1528. static byte readExtraFlags(ByteBuffer buffer, int offset, JetFormat format)
  1529. {
  1530. int extFlagsOffset = format.OFFSET_COLUMN_EXT_FLAGS;
  1531. return ((extFlagsOffset >= 0) ? buffer.get(offset + extFlagsOffset) : 0);
  1532. }
  1533. /**
  1534. * Writes the sort order info to the given buffer at the current position.
  1535. */
  1536. private static void writeSortOrder(ByteBuffer buffer, SortOrder sortOrder,
  1537. JetFormat format) {
  1538. if(sortOrder == null) {
  1539. sortOrder = format.DEFAULT_SORT_ORDER;
  1540. }
  1541. buffer.putShort(sortOrder.getValue());
  1542. if(format.SIZE_SORT_ORDER == 4) {
  1543. buffer.put((byte)0x00); // unknown
  1544. buffer.put(sortOrder.getVersion());
  1545. }
  1546. }
  1547. /**
  1548. * Returns {@code true} if the value is immutable, {@code false} otherwise.
  1549. * This only handles values that are returned from the {@link #read} method.
  1550. */
  1551. static boolean isImmutableValue(Object value) {
  1552. // for now, the only mutable value this class returns is byte[]
  1553. return !(value instanceof byte[]);
  1554. }
  1555. /**
  1556. * Converts the given value to the "internal" representation for the given
  1557. * data type.
  1558. */
  1559. public static Object toInternalValue(DataType dataType, Object value)
  1560. throws IOException
  1561. {
  1562. if(value == null) {
  1563. return null;
  1564. }
  1565. switch(dataType) {
  1566. case BOOLEAN:
  1567. return ((value instanceof Boolean) ? value : toBooleanValue(value));
  1568. case BYTE:
  1569. return ((value instanceof Byte) ? value : toNumber(value).byteValue());
  1570. case INT:
  1571. return ((value instanceof Short) ? value :
  1572. toNumber(value).shortValue());
  1573. case LONG:
  1574. return ((value instanceof Integer) ? value :
  1575. toNumber(value).intValue());
  1576. case MONEY:
  1577. return toBigDecimal(value);
  1578. case FLOAT:
  1579. return ((value instanceof Float) ? value :
  1580. toNumber(value).floatValue());
  1581. case DOUBLE:
  1582. return ((value instanceof Double) ? value :
  1583. toNumber(value).doubleValue());
  1584. case SHORT_DATE_TIME:
  1585. return ((value instanceof DateExt) ? value :
  1586. new Date(toDateLong(value)));
  1587. case TEXT:
  1588. case MEMO:
  1589. case GUID:
  1590. return ((value instanceof String) ? value :
  1591. toCharSequence(value).toString());
  1592. case NUMERIC:
  1593. return toBigDecimal(value);
  1594. case COMPLEX_TYPE:
  1595. // leave alone for now?
  1596. return value;
  1597. case BIG_INT:
  1598. return ((value instanceof Long) ? value :
  1599. toNumber(value).longValue());
  1600. default:
  1601. // some variation of binary data
  1602. return toByteArray(value);
  1603. }
  1604. }
  1605. String withErrorContext(String msg) {
  1606. return withErrorContext(msg, getDatabase(), getTable().getName(), getName());
  1607. }
  1608. private static String withErrorContext(
  1609. String msg, DatabaseImpl db, String tableName, String colName) {
  1610. return msg + " (Db=" + db.getName() + ";Table=" + tableName + ";Column=" +
  1611. colName + ")";
  1612. }
  1613. /**
  1614. * Date subclass which stashes the original date bits, in case we attempt to
  1615. * re-write the value (will not lose precision).
  1616. */
  1617. private static final class DateExt extends Date
  1618. {
  1619. private static final long serialVersionUID = 0L;
  1620. /** cached bits of the original date value */
  1621. private transient final long _dateBits;
  1622. private DateExt(long time, long dateBits) {
  1623. super(time);
  1624. _dateBits = dateBits;
  1625. }
  1626. public long getDateBits() {
  1627. return _dateBits;
  1628. }
  1629. private Object writeReplace() throws ObjectStreamException {
  1630. // if we are going to serialize this Date, convert it back to a normal
  1631. // Date (in case it is restored outside of the context of jackcess)
  1632. return new Date(super.getTime());
  1633. }
  1634. }
  1635. /**
  1636. * Wrapper for raw column data which can be re-written.
  1637. */
  1638. private static class RawData implements Serializable
  1639. {
  1640. private static final long serialVersionUID = 0L;
  1641. private final byte[] _bytes;
  1642. private RawData(byte[] bytes) {
  1643. _bytes = bytes;
  1644. }
  1645. private byte[] getBytes() {
  1646. return _bytes;
  1647. }
  1648. @Override
  1649. public String toString() {
  1650. return CustomToStringStyle.valueBuilder(this)
  1651. .append(null, getBytes())
  1652. .toString();
  1653. }
  1654. private Object writeReplace() throws ObjectStreamException {
  1655. // if we are going to serialize this, convert it back to a normal
  1656. // byte[] (in case it is restored outside of the context of jackcess)
  1657. return getBytes();
  1658. }
  1659. }
  1660. /**
  1661. * Base class for the supported autonumber types.
  1662. * @usage _advanced_class_
  1663. */
  1664. public abstract class AutoNumberGenerator
  1665. {
  1666. protected AutoNumberGenerator() {}
  1667. /**
  1668. * Returns the last autonumber generated by this generator. Only valid
  1669. * after a call to {@link Table#addRow}, otherwise undefined.
  1670. */
  1671. public abstract Object getLast();
  1672. /**
  1673. * Returns the next autonumber for this generator.
  1674. * <p>
  1675. * <i>Warning, calling this externally will result in this value being
  1676. * "lost" for the table.</i>
  1677. */
  1678. public abstract Object getNext(TableImpl.WriteRowState writeRowState);
  1679. /**
  1680. * Returns a valid autonumber for this generator.
  1681. * <p>
  1682. * <i>Warning, calling this externally may result in this value being
  1683. * "lost" for the table.</i>
  1684. */
  1685. public abstract Object handleInsert(
  1686. TableImpl.WriteRowState writeRowState, Object inRowValue)
  1687. throws IOException;
  1688. /**
  1689. * Restores a previous autonumber generated by this generator.
  1690. */
  1691. public abstract void restoreLast(Object last);
  1692. /**
  1693. * Returns the type of values generated by this generator.
  1694. */
  1695. public abstract DataType getType();
  1696. }
  1697. private final class LongAutoNumberGenerator extends AutoNumberGenerator
  1698. {
  1699. private LongAutoNumberGenerator() {}
  1700. @Override
  1701. public Object getLast() {
  1702. // the table stores the last long autonumber used
  1703. return getTable().getLastLongAutoNumber();
  1704. }
  1705. @Override
  1706. public Object getNext(TableImpl.WriteRowState writeRowState) {
  1707. // the table stores the last long autonumber used
  1708. return getTable().getNextLongAutoNumber();
  1709. }
  1710. @Override
  1711. public Object handleInsert(TableImpl.WriteRowState writeRowState,
  1712. Object inRowValue)
  1713. throws IOException
  1714. {
  1715. int inAutoNum = toNumber(inRowValue).intValue();
  1716. if(inAutoNum <= INVALID_AUTO_NUMBER && !getTable().isAllowAutoNumberInsert()) {
  1717. throw new IOException(withErrorContext(
  1718. "Invalid auto number value " + inAutoNum));
  1719. }
  1720. // the table stores the last long autonumber used
  1721. getTable().adjustLongAutoNumber(inAutoNum);
  1722. return inAutoNum;
  1723. }
  1724. @Override
  1725. public void restoreLast(Object last) {
  1726. if(last instanceof Integer) {
  1727. getTable().restoreLastLongAutoNumber((Integer)last);
  1728. }
  1729. }
  1730. @Override
  1731. public DataType getType() {
  1732. return DataType.LONG;
  1733. }
  1734. }
  1735. private final class GuidAutoNumberGenerator extends AutoNumberGenerator
  1736. {
  1737. private Object _lastAutoNumber;
  1738. private GuidAutoNumberGenerator() {}
  1739. @Override
  1740. public Object getLast() {
  1741. return _lastAutoNumber;
  1742. }
  1743. @Override
  1744. public Object getNext(TableImpl.WriteRowState writeRowState) {
  1745. // format guids consistently w/ Column.readGUIDValue()
  1746. _lastAutoNumber = "{" + UUID.randomUUID() + "}";
  1747. return _lastAutoNumber;
  1748. }
  1749. @Override
  1750. public Object handleInsert(TableImpl.WriteRowState writeRowState,
  1751. Object inRowValue)
  1752. throws IOException
  1753. {
  1754. _lastAutoNumber = toCharSequence(inRowValue);
  1755. return _lastAutoNumber;
  1756. }
  1757. @Override
  1758. public void restoreLast(Object last) {
  1759. _lastAutoNumber = null;
  1760. }
  1761. @Override
  1762. public DataType getType() {
  1763. return DataType.GUID;
  1764. }
  1765. }
  1766. private final class ComplexTypeAutoNumberGenerator extends AutoNumberGenerator
  1767. {
  1768. private ComplexTypeAutoNumberGenerator() {}
  1769. @Override
  1770. public Object getLast() {
  1771. // the table stores the last ComplexType autonumber used
  1772. return getTable().getLastComplexTypeAutoNumber();
  1773. }
  1774. @Override
  1775. public Object getNext(TableImpl.WriteRowState writeRowState) {
  1776. // same value is shared across all ComplexType values in a row
  1777. int nextComplexAutoNum = writeRowState.getComplexAutoNumber();
  1778. if(nextComplexAutoNum <= INVALID_AUTO_NUMBER) {
  1779. // the table stores the last ComplexType autonumber used
  1780. nextComplexAutoNum = getTable().getNextComplexTypeAutoNumber();
  1781. writeRowState.setComplexAutoNumber(nextComplexAutoNum);
  1782. }
  1783. return new ComplexValueForeignKeyImpl(ColumnImpl.this,
  1784. nextComplexAutoNum);
  1785. }
  1786. @Override
  1787. public Object handleInsert(TableImpl.WriteRowState writeRowState,
  1788. Object inRowValue)
  1789. throws IOException
  1790. {
  1791. ComplexValueForeignKey inComplexFK = null;
  1792. if(inRowValue instanceof ComplexValueForeignKey) {
  1793. inComplexFK = (ComplexValueForeignKey)inRowValue;
  1794. } else {
  1795. inComplexFK = new ComplexValueForeignKeyImpl(
  1796. ColumnImpl.this, toNumber(inRowValue).intValue());
  1797. }
  1798. if(inComplexFK.getColumn() != ColumnImpl.this) {
  1799. throw new IOException(withErrorContext(
  1800. "Wrong column for complex value foreign key, found " +
  1801. inComplexFK.getColumn().getName()));
  1802. }
  1803. if(inComplexFK.get() < 1) {
  1804. throw new IOException(withErrorContext(
  1805. "Invalid complex value foreign key value " + inComplexFK.get()));
  1806. }
  1807. // same value is shared across all ComplexType values in a row
  1808. int prevRowValue = writeRowState.getComplexAutoNumber();
  1809. if(prevRowValue <= INVALID_AUTO_NUMBER) {
  1810. writeRowState.setComplexAutoNumber(inComplexFK.get());
  1811. } else if(prevRowValue != inComplexFK.get()) {
  1812. throw new IOException(withErrorContext(
  1813. "Inconsistent complex value foreign key values: found " +
  1814. prevRowValue + ", given " + inComplexFK));
  1815. }
  1816. // the table stores the last ComplexType autonumber used
  1817. getTable().adjustComplexTypeAutoNumber(inComplexFK.get());
  1818. return inComplexFK;
  1819. }
  1820. @Override
  1821. public void restoreLast(Object last) {
  1822. if(last instanceof ComplexValueForeignKey) {
  1823. getTable().restoreLastComplexTypeAutoNumber(
  1824. ((ComplexValueForeignKey)last).get());
  1825. }
  1826. }
  1827. @Override
  1828. public DataType getType() {
  1829. return DataType.COMPLEX_TYPE;
  1830. }
  1831. }
  1832. private final class UnsupportedAutoNumberGenerator extends AutoNumberGenerator
  1833. {
  1834. private final DataType _genType;
  1835. private UnsupportedAutoNumberGenerator(DataType genType) {
  1836. _genType = genType;
  1837. }
  1838. @Override
  1839. public Object getLast() {
  1840. return null;
  1841. }
  1842. @Override
  1843. public Object getNext(TableImpl.WriteRowState writeRowState) {
  1844. throw new UnsupportedOperationException();
  1845. }
  1846. @Override
  1847. public Object handleInsert(TableImpl.WriteRowState writeRowState,
  1848. Object inRowValue) {
  1849. throw new UnsupportedOperationException();
  1850. }
  1851. @Override
  1852. public void restoreLast(Object last) {
  1853. throw new UnsupportedOperationException();
  1854. }
  1855. @Override
  1856. public DataType getType() {
  1857. return _genType;
  1858. }
  1859. }
  1860. /**
  1861. * Information about the sort order (collation) for a textual column.
  1862. * @usage _intermediate_class_
  1863. */
  1864. public static final class SortOrder
  1865. {
  1866. private final short _value;
  1867. private final byte _version;
  1868. public SortOrder(short value, byte version) {
  1869. _value = value;
  1870. _version = version;
  1871. }
  1872. public short getValue() {
  1873. return _value;
  1874. }
  1875. public byte getVersion() {
  1876. return _version;
  1877. }
  1878. @Override
  1879. public int hashCode() {
  1880. return _value;
  1881. }
  1882. @Override
  1883. public boolean equals(Object o) {
  1884. return ((this == o) ||
  1885. ((o != null) && (getClass() == o.getClass()) &&
  1886. (_value == ((SortOrder)o)._value) &&
  1887. (_version == ((SortOrder)o)._version)));
  1888. }
  1889. @Override
  1890. public String toString() {
  1891. return CustomToStringStyle.valueBuilder(this)
  1892. .append(null, _value + "(" + _version + ")")
  1893. .toString();
  1894. }
  1895. }
  1896. /**
  1897. * Utility struct for passing params through ColumnImpl constructors.
  1898. */
  1899. static final class InitArgs
  1900. {
  1901. public final TableImpl table;
  1902. public final ByteBuffer buffer;
  1903. public final int offset;
  1904. public final String name;
  1905. public final int displayIndex;
  1906. public final byte colType;
  1907. public final byte flags;
  1908. public final byte extFlags;
  1909. public DataType type;
  1910. InitArgs(TableImpl table, ByteBuffer buffer, int offset, String name,
  1911. int displayIndex) {
  1912. this.table = table;
  1913. this.buffer = buffer;
  1914. this.offset = offset;
  1915. this.name = name;
  1916. this.displayIndex = displayIndex;
  1917. this.colType = buffer.get(offset + table.getFormat().OFFSET_COLUMN_TYPE);
  1918. this.flags = buffer.get(offset + table.getFormat().OFFSET_COLUMN_FLAGS);
  1919. this.extFlags = readExtraFlags(buffer, offset, table.getFormat());
  1920. }
  1921. }
  1922. }