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 72KB

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