提交 02176ff1 authored 作者: Max Englander's avatar Max Englander

enum-support: add docs

上级 e8d00a2c
...@@ -1921,7 +1921,7 @@ CALL CSVWRITE('test2.csv', 'SELECT * FROM TEST', 'charset=UTF-8 fieldSeparator=| ...@@ -1921,7 +1921,7 @@ CALL CSVWRITE('test2.csv', 'SELECT * FROM TEST', 'charset=UTF-8 fieldSeparator=|
intType | booleanType | tinyintType | smallintType | bigintType | identityType intType | booleanType | tinyintType | smallintType | bigintType | identityType
| decimalType | doubleType | realType | dateType | timeType | timestampType | decimalType | doubleType | realType | dateType | timeType | timestampType
| binaryType | otherType | varcharType | varcharIgnorecaseType | charType | binaryType | otherType | varcharType | varcharIgnorecaseType | charType
| blobType | clobType | uuidType | arrayType | blobType | clobType | uuidType | arrayType | enumType
"," ","
A data type definition. A data type definition.
"," ","
...@@ -2509,6 +2509,20 @@ and ""ResultSet.getObject(..)"" or ""ResultSet.getArray(..)"" to retrieve the va ...@@ -2509,6 +2509,20 @@ and ""ResultSet.getObject(..)"" or ""ResultSet.getArray(..)"" to retrieve the va
ARRAY ARRAY
" "
"Data Types","ENUM Type","
{ ENUM (string [, ... ]) }
","
A type with enumerated values.
Mapped to ""java.lang.Integer"".
The first provided value is mapped to 0, the
second mapped to 1, and so on.
Duplicate and empty values are not permitted.
","
ENUM('clubs', 'diamonds', 'hearts', 'spades')
"
"Data Types","GEOMETRY Type"," "Data Types","GEOMETRY Type","
GEOMETRY GEOMETRY
"," ","
......
...@@ -25,6 +25,8 @@ Change Log ...@@ -25,6 +25,8 @@ Change Log
</li> </li>
<li>Added support for invisible columns. <li>Added support for invisible columns.
</li> </li>
<li>Added an ENUM data type, with syntax similar to that of MySQL and Oracle.
</li>
</ul> </ul>
<h2>Version 1.4.194 (2017-03-10)</h2> <h2>Version 1.4.194 (2017-03-10)</h2>
......
...@@ -606,7 +606,7 @@ Optional parameters for CSVREAD and CSVWRITE." ...@@ -606,7 +606,7 @@ Optional parameters for CSVREAD and CSVWRITE."
intType | booleanType | tinyintType | smallintType | bigintType | identityType intType | booleanType | tinyintType | smallintType | bigintType | identityType
| decimalType | doubleType | realType | dateType | timeType | timestampType | decimalType | doubleType | realType | dateType | timeType | timestampType
| binaryType | otherType | varcharType | varcharIgnorecaseType | charType | binaryType | otherType | varcharType | varcharIgnorecaseType | charType
| blobType | clobType | uuidType | arrayType | blobType | clobType | uuidType | arrayType | enumType
"," ","
A data type definition." A data type definition."
"Other Grammar","Date"," "Other Grammar","Date","
...@@ -834,6 +834,10 @@ Universally unique identifier." ...@@ -834,6 +834,10 @@ Universally unique identifier."
ARRAY ARRAY
"," ","
An array of values." An array of values."
"Data Types","ENUM Type","
{ ENUM (string [, ... ]) }
","
A type with enumerated values."
"Data Types","GEOMETRY Type"," "Data Types","GEOMETRY Type","
GEOMETRY GEOMETRY
"," ","
......
...@@ -22,6 +22,12 @@ public class ValueEnum extends ValueEnumBase { ...@@ -22,6 +22,12 @@ public class ValueEnum extends ValueEnumBase {
this.enumerators = enumerators; this.enumerators = enumerators;
} }
/**
* Check for any violations, such as empty
* values, duplicate values.
*
* @param enumerators the enumerators
*/
public static final void check(final String[] enumerators) { public static final void check(final String[] enumerators) {
switch (validate(enumerators)) { switch (validate(enumerators)) {
case VALID: case VALID:
...@@ -52,9 +58,17 @@ public class ValueEnum extends ValueEnumBase { ...@@ -52,9 +58,17 @@ public class ValueEnum extends ValueEnumBase {
@Override @Override
protected int compareSecure(final Value v, final CompareMode mode) { protected int compareSecure(final Value v, final CompareMode mode) {
final ValueEnum ev = ValueEnum.get(enumerators, v); final ValueEnum ev = ValueEnum.get(enumerators, v);
return MathUtils.compareInt(ordinal(), ev.ordinal()); return MathUtils.compareInt(getInt(), ev.getInt());
} }
/**
* Create an ENUM value from the provided enumerators
* and value.
*
* @param enumerators the enumerators
* @param value a value
* @return the ENUM value
*/
public static ValueEnum get(final String[] enumerators, final Value value) { public static ValueEnum get(final String[] enumerators, final Value value) {
check(enumerators, value); check(enumerators, value);
...@@ -76,6 +90,14 @@ public class ValueEnum extends ValueEnumBase { ...@@ -76,6 +90,14 @@ public class ValueEnum extends ValueEnumBase {
return enumerators; return enumerators;
} }
/**
* Evaluates whether a valid ENUM can be constructed
* from the provided enumerators and value.
*
* @param enumerators the enumerators
* @param value the value
* @return whether a valid ENUM can be constructed from the provided values
*/
public static boolean isValid(final String enumerators[], final Value value) { public static boolean isValid(final String enumerators[], final Value value) {
return validate(enumerators, value).equals(Validation.VALID); return validate(enumerators, value).equals(Validation.VALID);
} }
...@@ -84,7 +106,7 @@ public class ValueEnum extends ValueEnumBase { ...@@ -84,7 +106,7 @@ public class ValueEnum extends ValueEnumBase {
return label == null ? null : label.trim().toUpperCase(Locale.ENGLISH); return label == null ? null : label.trim().toUpperCase(Locale.ENGLISH);
} }
public static String[] sanitize(final String[] enumerators) { private static String[] sanitize(final String[] enumerators) {
if (enumerators == null || enumerators.length == 0) return null; if (enumerators == null || enumerators.length == 0) return null;
final String[] clean = new String[enumerators.length]; final String[] clean = new String[enumerators.length];
......
...@@ -7,9 +7,15 @@ import java.util.Locale; ...@@ -7,9 +7,15 @@ import java.util.Locale;
import org.h2.message.DbException; import org.h2.message.DbException;
import org.h2.util.MathUtils; import org.h2.util.MathUtils;
/**
* Base implementation of the ENUM data type.
*
* Currently, this class is used primarily for
* client-server communication.
*/
public class ValueEnumBase extends Value { public class ValueEnumBase extends Value {
public static final int PRECISION = 10; private static final int PRECISION = 10;
public static final int DISPLAY_SIZE = 11; private static final int DISPLAY_SIZE = 11;
private final String label; private final String label;
private final int ordinal; private final int ordinal;
...@@ -27,7 +33,7 @@ public class ValueEnumBase extends Value { ...@@ -27,7 +33,7 @@ public class ValueEnumBase extends Value {
@Override @Override
protected int compareSecure(final Value v, final CompareMode mode) { protected int compareSecure(final Value v, final CompareMode mode) {
return MathUtils.compareInt(ordinal(), v.getInt()); return MathUtils.compareInt(getInt(), v.getInt());
} }
@Override @Override
...@@ -39,9 +45,16 @@ public class ValueEnumBase extends Value { ...@@ -39,9 +45,16 @@ public class ValueEnumBase extends Value {
@Override @Override
public boolean equals(final Object other) { public boolean equals(final Object other) {
return other instanceof ValueEnumBase && return other instanceof ValueEnumBase &&
ordinal() == ((ValueEnumBase) other).ordinal(); getInt() == ((ValueEnumBase) other).getInt();
} }
/**
* Get or create an enum value with the given label and ordinal.
*
* @param label the label
* @param ordinal the ordinal
* @return the value
*/
public static ValueEnumBase get(final String label, final int ordinal) { public static ValueEnumBase get(final String label, final int ordinal) {
return new ValueEnumBase(label, ordinal); return new ValueEnumBase(label, ordinal);
} }
...@@ -95,7 +108,7 @@ public class ValueEnumBase extends Value { ...@@ -95,7 +108,7 @@ public class ValueEnumBase extends Value {
public int hashCode() { public int hashCode() {
int results = 31; int results = 31;
results += getString().hashCode(); results += getString().hashCode();
results += ordinal(); results += getInt();
return results; return results;
} }
...@@ -112,10 +125,6 @@ public class ValueEnumBase extends Value { ...@@ -112,10 +125,6 @@ public class ValueEnumBase extends Value {
} }
protected int ordinal() {
return ordinal;
}
@Override @Override
public void set(final PreparedStatement prep, final int parameterIndex) public void set(final PreparedStatement prep, final int parameterIndex)
throws SQLException { throws SQLException {
......
...@@ -448,7 +448,7 @@ public class TestPreparedStatement extends TestBase { ...@@ -448,7 +448,7 @@ public class TestPreparedStatement extends TestBase {
Statement stat = conn.createStatement(); Statement stat = conn.createStatement();
stat.execute("CREATE TABLE test_enum(size ENUM('small', 'medium', 'large'))"); stat.execute("CREATE TABLE test_enum(size ENUM('small', 'medium', 'large'))");
String[] badSizes = new String[]{"green", "smalll", "0"}; String[] badSizes = new String[]{"green", "smol", "0"};
for (int i = 0; i < badSizes.length; i++) { for (int i = 0; i < badSizes.length; i++) {
PreparedStatement prep = conn.prepareStatement( PreparedStatement prep = conn.prepareStatement(
"INSERT INTO test_enum VALUES(?)"); "INSERT INTO test_enum VALUES(?)");
......
...@@ -76,7 +76,7 @@ calculation calculations calendar calendars call callable callback callbacks ...@@ -76,7 +76,7 @@ calculation calculations calendar calendars call callable callback callbacks
called caller calling calls cally caload came camel can cancel canceled canceling called caller calling calls cally caload came camel can cancel canceled canceling
cancellation cancelled cancels candidates cannot canonical cap capabilities cancellation cancelled cancels candidates cannot canonical cap capabilities
capability capacity capitalization capitalize capitalized capone caps capture capability capacity capitalization capitalize capitalized capone caps capture
captured car cardinal cardinality care careful carriage carrier cars cartesian captured car card cardinal cardinality care careful carriage carrier cars cartesian
cascade cascading case cases casesensitive casewhen cash casing casqueiro cast cascade cascading case cases casesensitive casewhen cash casing casqueiro cast
casting castore cat catalina catalog catalogs cataloguing catch catcher catches casting castore cat catalina catalog catalogs cataloguing catch catcher catches
catching category catlog caucho caught cause caused causes causing cavestro catching category catlog caucho caught cause caused causes causing cavestro
...@@ -181,8 +181,8 @@ detailed details detect detected detecting detection detector detects determine ...@@ -181,8 +181,8 @@ detailed details detect detected detecting detection detector detects determine
determining deterministic detrimental deusen deutsch dev develop developed determining deterministic detrimental deusen deutsch dev develop developed
developer developers developing development devenish deviation device devices developer developers developing development devenish deviation device devices
dfile dgenerate dgroup dhe dhis diabetes diagnostic diagnostics diagram diagrams dfile dgenerate dgroup dhe dhis diabetes diagnostic diagnostics diagram diagrams
dialect dialog diams dick dictionary did didn died dieguez diehard dies diff dialect dialog diamonds diams dick dictionary did didn died dieguez diehard dies
differ difference differences different differential differentiate differently diff differ difference differences different differential differentiate differently
differs dig digest digit digital digits diligence dim dimension dimensional differs dig digest digit digital digits diligence dim dimension dimensional
dimensions dimitrijs dinamica dining dip dips dir direct direction directly dimensions dimitrijs dinamica dining dip dips dir direct direction directly
directories directory directs dirname dirs dirty disable disabled directories directory directs dirname dirs dirty disable disabled
...@@ -218,14 +218,14 @@ encrypting encryption encrypts end ended enderbury endif ending endings endless ...@@ -218,14 +218,14 @@ encrypting encryption encrypts end ended enderbury endif ending endings endless
endlessly endorse ends enforce enforceability enforceable enforced engine engines endlessly endorse ends enforce enforceability enforceable enforced engine engines
english enhance enhanced enhancement enhancer enlarge enough enqueued ensp ensure english enhance enhanced enhancement enhancer enlarge enough enqueued ensp ensure
ensures ensuring enter entered entering enterprise entire entities entity entries ensures ensuring enter entered entering enterprise entire entities entity entries
entry enum enumerate enumeration env envelope environment environments enwiki eof entry enum enumerate enumerated enumerator enumerators enumeration env envelope
eol epl epoch epoll epsilon equal equality equally equals equipment equitable environment environments enwiki eof eol epl epoch epoll epsilon equal equality equally
equiv equivalent equivalents era erable eremainder eric erik err error errorlevel equals equipment equitable equiv equivalent equivalents era erable eremainder eric
errors erwan ery esc escape escaped escapes escaping escargots ese espa essential erik err error errorlevel errors erwan ery esc escape escaped escapes escaping
essentials established estimate estimated estimates estimating estimation escargots ese espa essential essentials established estimate estimated estimates
estoppel eta etc eth etl euml euro europe europeu euros eva eval evaluatable estimating estimation estoppel eta etc eth etl euml euro europe europeu euros eva eval
evaluate evaluated evaluates evaluating evaluation evdokimov even evenly event evaluatable evaluate evaluated evaluates evaluating evaluation evdokimov even evenly
events eventually ever every everybody everyone everything everywhere evict event events eventually ever every everybody everyone everything everywhere evict
evicted eviction evolving exact exactly example examples exceed exceeded exceeds evicted eviction evolving exact exactly example examples exceed exceeded exceeds
excel except exception exceptions exchange exclude excluded excludes excluding excel except exception exceptions exchange exclude excluded excludes excluding
exclusion exclusive exclusively exe exec executable executables execute executed exclusion exclusive exclusively exe exec executable executables execute executed
...@@ -277,7 +277,7 @@ google googlegroups got goto goubard governed governing government gpg grabbing ...@@ -277,7 +277,7 @@ google googlegroups got goto goubard governed governing government gpg grabbing
graceful graf grails grained grains grajcar grammar grammars grandin grandma graceful graf grails grained grains grajcar grammar grammars grandin grandma
grant grantable granted grantedrole grantee granteetype granting grantor grants grant grantable granted grantedrole grantee granteetype granting grantor grants
granularity graph graphic graphical graphics grass gray great greater greatest granularity graph graphic graphical graphics grass gray great greater greatest
greatly gredler greece greedy gregorian grep grew grid gridwidth gridx gridy greatly gredler greece greedy green gregorian grep grew grid gridwidth gridx gridy
groove groovy gross group grouped grouping groups groupware grover grow growing groove groovy gross group grouped grouping groups groupware grover grow growing
grows growth guarantee guaranteed guard guardian guess guesses guest gui guid grows growth guarantee guaranteed guard guardian guess guesses guest gui guid
guide guidelines guides gumbo gustav gutierrez gzip hack had haidinyak half hallo guide guidelines guides gumbo gustav gutierrez gzip hack had haidinyak half hallo
...@@ -485,9 +485,9 @@ predict predicted prediction prefer preferable preferdoslikelineends preferences ...@@ -485,9 +485,9 @@ predict predicted prediction prefer preferable preferdoslikelineends preferences
preferred prefix prefixes prefs premain premature prep prepare prepared prepares preferred prefix prefixes prefs premain premature prep prepare prepared prepares
preparing prepended prepending pres presence present presentation preserve preparing prepended prepending pres presence present presentation preserve
preserved preserving press pressed pretty prev prevent prevented prevention preserved preserving press pressed pretty prev prevent prevented prevention
prevents previous previously pri price prices primary prime primitive primitives prevents previous previously pri price prices primarily primary prime primitive
principal print printable printed printf printing println prints prio prior primitives principal print printable printed printf printing println prints prio
prioritize priority private privilege privileges pro prob probability probable prior prioritize priority private privilege privileges pro prob probability probable
probably problem problematic problems proc procedural procedure procedures probably problem problematic problems proc procedural procedure procedures
proceed process processed processes processing processor processors procurement proceed process processed processes processing processor processors procurement
prod produce produced produces product production products prof profile profiler prod produce produced produces product production products prof profile profiler
...@@ -558,7 +558,7 @@ routines row rowcount rowid rowlock rownum rows rowscn rowsize roy royalty rpad ...@@ -558,7 +558,7 @@ routines row rowcount rowid rowlock rownum rows rowscn rowsize roy royalty rpad
rsaquo rsquo rss rtree rtrim ruby ruebezahl rule rules run rund rundll runnable rsaquo rsquo rss rtree rtrim ruby ruebezahl rule rules run rund rundll runnable
runner runners running runs runscript runtime rwd rws sabine safari safe safely runner runners running runs runscript runtime rwd rws sabine safari safe safely
safes safety said sainsbury salary sale sales saload salt salz sam same safes safety said sainsbury salary sale sales saload salt salz sam same
sameorigin samp sample samples sanity sans sastore sat satisfy saturday sauce sameorigin samp sample samples sanitize sanity sans sastore sat satisfy saturday sauce
sauerkraut sava save saved savepoint savepoints saves saving savings say saying sauerkraut sava save saved savepoint savepoints saves saving savings say saying
says sbquo scala scalability scalable scalar scale scaled scales scan scanned says sbquo scala scalability scalable scalar scale scaled scales scan scanned
scanner scanners scanning scans scapegoat scc schedule scheduler schem schema scanner scanners scanning scans scapegoat scc schedule scheduler schem schema
...@@ -591,7 +591,7 @@ sites situation situations six sixty size sized sizeof sizes sizing skeletons sk ...@@ -591,7 +591,7 @@ sites situation situations six sixty size sized sizeof sizes sizing skeletons sk
skiing skill skip skipped skipping skips sky slash slashdot slashes slave sleep skiing skill skip skipped skipping skips sky slash slashdot slashes slave sleep
sleeping sleeps slept slice sliced slight slightly slist slot slots slovensky sleeping sleeps slept slice sliced slight slightly slist slot slots slovensky
slow slowed slower slowest slowing slowly slows small smalldatetime smaller slow slowed slower slowest slowing slowly slows small smalldatetime smaller
smallest smallint smart smith smtp smtps smuggled snapshot snapshots snipped smallest smallint smart smith smol smtp smtps smuggled snake snapshot snapshots snipped
snippet snippets soap social socket sockets soerensen soffice soft software sold snippet snippets soap social socket sockets soerensen soffice soft software sold
sole solely solid solo solution solutions solve solved solves solving some sole solely solid solo solution solutions solve solved solves solving some
somebody somehow someone something sometime sometimes somewhat somewhere song somebody somehow someone something sometime sometimes somewhat somewhere song
...@@ -621,8 +621,8 @@ subscribe subselect subsequent subsequently subset substance substitute ...@@ -621,8 +621,8 @@ subscribe subselect subsequent subsequently subset substance substitute
substituted substitution substr substring substrings substructure subsystem substituted substitution substr substring substrings substructure subsystem
subtract subtracted subtracting subtraction subversion succeed succeeded succeeds subtract subtracted subtracting subtraction subversion succeed succeeded succeeds
success successful successfully succession such suddenly sudo sue sufficient success successful successfully succession such suddenly sudo sue sufficient
sufficiently suffix sugar suggest suggested suggestion suggestions suitable suite sufficiently suffix sugar suggest suggested suggestion suggestions suit suitable
suites sullivan sum summand summary summer summertime sums sun sunday sup supe suite suites sullivan sum summand summary summer summertime sums sun sunday sup supe
super superclass superfluous superinterfaces superior superseded supertable super superclass superfluous superinterfaces superior superseded supertable
superuser supplemental supplied supplier supply support supported supporter superuser supplemental supplied supplier supply support supported supporter
supporters supporting supports supposed suppress sure surname surrogate supporters supporting supports supposed suppress sure surname surrogate
...@@ -666,7 +666,7 @@ trick tricky tried tries trig trigger triggered triggers trigonometric trim ...@@ -666,7 +666,7 @@ trick tricky tried tries trig trigger triggered triggers trigonometric trim
trimmed trims trip trivial trouble true trunc truncate truncated truncates trimmed trims trip trivial trouble true trunc truncate truncated truncates
truncating truncation trunk trust trusted trx try trying tsi tsmsys tsv tucc truncating truncation trunk trust trusted trx try trying tsi tsmsys tsv tucc
tucker tuesday tune tunes tuning turkel turkish turn turned turns tutorial tweak tucker tuesday tune tunes tuning turkel turkish turn turned turns tutorial tweak
tweaking tweet twelve twice twitter two txt tymczak type typeof types typesafe tweaking tweet twelve twice twitter two txt tymczak type typed typeof types typesafe
typical typically typing typlen typname typo typos typtypmod tzd tzh tzm tzr typical typically typing typlen typname typo typos typtypmod tzd tzh tzm tzr
uacute uarr ubuntu ucase ucb ucirc ucs udt udts uffff ugly ugrave uid uint ujint uacute uarr ubuntu ucase ucb ucirc ucs udt udts uffff ugly ugrave uid uint ujint
ujlong ulimit uml umlaut umr unable unaligned unary unavailability unbound ujlong ulimit uml umlaut umr unable unaligned unary unavailability unbound
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论