01: package simpleorm.core;
02:
03: /**
04: * Generate keys using rows in a separate sequence table.
05: * This should be done in a separate transaction to avoid locking problems.
06: */
07:
08: public abstract class SGenerator {
09: protected SRecordMeta record;
10:
11: public SGenerator(SRecordMeta record) {
12: this .record = record;
13: }
14:
15: /**
16: * Create a new record with a generated key.
17: */
18: public SRecordInstance createWithGeneratedKey(SRecordMeta meta,
19: SFieldMeta keyField) {
20:
21: if (meta != record)
22: throw new SException.Error("Inconsistent record metas "
23: + record + " !=" + meta);
24: /// Generate the key.
25: long gened = generateKey(meta, keyField);
26:
27: /// Create the new record.
28: SRecordInstance newRec = meta.create(SJSharp.newLong(gened));
29:
30: if (SLog.slog.enableQueries())
31: SLog.slog.queries("createWithGeneratedKey: " + newRec);
32:
33: return newRec;
34: }
35:
36: /**
37: * Update instance with a newly generated key.
38: * For example, when reattaching a record.
39: * ### needs to be unified with createWithGeneratedKey!
40: * The hard one is the Insert Identity.
41: */
42: void updateWithGeneratedKey(SRecordInstance instance,
43: SFieldMeta keyField) {
44:
45: SRecordMeta meta = instance.getMeta();
46: if (meta != record)
47: throw new SException.Error("Inconsistent record metas "
48: + record + " !=" + meta);
49:
50: /// Generate the key.
51: long gened = generateKey(meta, keyField);
52:
53: instance.setLong(keyField, gened);
54:
55: if (SLog.slog.enableQueries())
56: SLog.slog.queries("updateWithGeneratedKey: " + instance);
57: }
58:
59: protected abstract long generateKey(SRecordMeta meta,
60: SFieldMeta keyField);
61:
62: /** returns DDL required to support number generation,
63: * Eg. "CREATE SEQUENCE FOO..."
64: * Returns a string rather than just doing it so that
65: * the caller can create a DDL file if they want to.
66: */
67: public String createDDL() {
68: return null;
69: }
70:
71: public String dropDDL() {
72: return null;
73: }
74: }
|