01: package simpleorm.core;
02:
03: import simpleorm.properties.*;
04: import java.sql.ResultSet;
05:
06: /**
07: * Booleans are represented as Boolean.TRUE/FALSE internally.
08: * However, SQL89 does not have a concept of boolean, only strings
09: * and numbers. So these are normally mapped to strings like "Y", "N".
10: * Which representation is determined in subclasses.
11: * (The JDBC java docs are useless as always "getBoolean gets booleans...").<p>
12:
13: (The issue is with JDBC, not SimpleORM. And of course SFieldObject
14: can always be used if really needed.) */
15:
16: public abstract class SFieldBoolean extends SFieldScalar {
17: public SFieldBoolean(SRecordMeta meta, String columnName,
18: SPropertyValue[] pvals) {
19: super (meta, columnName, pvals);
20: }
21:
22: /**
23: * Converts from the users external representation to
24: * the internal representation stored in SRecordInstance.
25: * This is deliberately quite permissive, and should work even
26: * if the external world is a bit inconsistent.
27: */
28: Object convertToField(Object raw) // In SFieldBoolean
29: {
30: return convertExternalToBoolean(raw);
31: }
32:
33: /**
34: * Shared routine for converting database representations to booleans so all boolean
35: * implementations can be consistent and so boolean classes can be attached to existing
36: * database columns
37: */
38: protected Object convertDatabaseToBoolean(ResultSet rs, int sqlIndex)
39: throws Exception {
40: // Only a default.
41: return convertExternalToBoolean(rs.getObject(sqlIndex));
42: }
43:
44: /**
45: * Shared routine for converting Strings to booleans so all boolean
46: * implementations can be consistent.
47: */
48: protected Boolean convertExternalToBoolean(Object raw) {
49: if (raw == null)
50: return null;
51: else if (raw instanceof Boolean)
52: return (Boolean) raw;
53: else if (raw instanceof String) {
54: String s = (String) raw;
55: if ("t".equalsIgnoreCase(s) || "true".equalsIgnoreCase(s)
56: || "y".equalsIgnoreCase(s)
57: || "yes".equalsIgnoreCase(s))
58: return Boolean.TRUE;
59: else if ("f".equalsIgnoreCase(s)
60: || "false".equalsIgnoreCase(s)
61: || "n".equalsIgnoreCase(s)
62: || "no".equalsIgnoreCase(s))
63: return Boolean.FALSE;
64: else
65: throw new SException.Error(
66: "String \""
67: + s
68: + "\" could not be converted to a java.lang.Boolean");
69: } else if (raw instanceof Number) {
70: int i = ((Number) raw).intValue();
71: return i != 0 ? Boolean.TRUE : Boolean.FALSE;
72: } else
73: throw new SException.Error("Cannot Convert '" + raw
74: + "' to Boolean.");
75: }
76: }
|