use of ru.curs.celesta.score.Grain in project celesta by CourseOrchestra.
the class DbUpdater method updateDb.
/**
* Performs update of DB structure based on the decomposed object model.
*/
public void updateDb() {
String sysSchemaName = score.getSysSchemaName();
try (T context = createContext()) {
updateSystemSchema(context);
// Теперь собираем в память информацию о гранулах на основании того,
// что
// хранится в таблице grains.
Map<String, GrainInfo> dbGrains = new HashMap<>();
while (schemaCursor.nextInSet()) {
if (!(EXPECTED_STATUSES.contains(schemaCursor.getState()))) {
throw new CelestaException("Cannot proceed with database upgrade: there are %s " + "not in 'ready', 'recover' or 'lock' state.", getSchemasTableName());
}
GrainInfo gi = new GrainInfo();
gi.checksum = (int) Long.parseLong(schemaCursor.getChecksum(), 16);
gi.length = schemaCursor.getLength();
gi.recover = schemaCursor.getState() == ISchemaCursor.RECOVER;
gi.lock = schemaCursor.getState() == ISchemaCursor.LOCK;
try {
gi.version = new VersionString(schemaCursor.getVersion());
} catch (ParseException e) {
throw new CelestaException(String.format("Error while scanning %s.%s table: %s", sysSchemaName, getSchemasTableName(), e.getMessage()));
}
dbGrains.put(schemaCursor.getId(), gi);
}
// Получаем список гранул на основе метамодели и сортируем его по
// порядку зависимости.
List<Grain> grains = new ArrayList<>(score.getGrains().values());
Collections.sort(grains, GRAIN_COMPARATOR);
// Выполняем итерацию по гранулам.
boolean success = true;
for (Grain g : grains) {
if (!g.isAutoupdate()) {
continue;
}
// Запись о грануле есть?
GrainInfo gi = dbGrains.get(g.getName());
if (gi == null) {
insertGrainRec(g);
success = updateGrain(g, connectionPool) & success;
} else {
// Запись есть -- решение об апгрейде принимается на основе
// версии и контрольной суммы.
success = decideToUpgrade(g, gi, connectionPool) & success;
}
}
if (!success) {
throw new CelestaException("Not all %s were updated successfully, see %s.%s table data for details.", getSchemasTableName(), sysSchemaName, getSchemasTableName());
}
}
}
use of ru.curs.celesta.score.Grain in project celesta by CourseOrchestra.
the class FirebirdAdaptor method processDefaults.
private void processDefaults(Connection conn, Column<?> c, DbColumnInfo dbColumnInfo) throws SQLException {
String defaultValue = null;
TableElement te = c.getParentTable();
Grain g = te.getGrain();
String sql = String.format("SELECT r.RDB$DEFAULT_SOURCE AS column_default_value%n" + " FROM RDB$RELATION_FIELDS r%n" + " WHERE r.RDB$RELATION_NAME='%s_%s' AND r.RDB$FIELD_NAME = '%s'", c.getParentTable().getGrain().getName(), c.getParentTable().getName(), c.getName());
try (ResultSet rs = SqlUtils.executeQuery(conn, sql)) {
rs.next();
String defaultSource = rs.getString(1);
if (defaultSource == null) {
if (IntegerColumn.class.equals(dbColumnInfo.getType())) {
String triggerName = SchemalessFunctions.generateSequenceTriggerName((IntegerColumn) c);
sql = String.format("SELECT proc.RDB$DEPENDED_ON_NAME %n " + "FROM RDB$DEPENDENCIES tr%n " + "JOIN RDB$DEPENDENCIES proc ON tr.RDB$DEPENDED_ON_NAME = proc.RDB$DEPENDENT_NAME%n " + "WHERE tr.RDB$DEPENDENT_NAME = '%s' AND tr.RDB$DEPENDENT_TYPE = 2 " + "AND tr.RDB$DEPENDED_ON_TYPE = 5%n " + "AND proc.RDB$DEPENDENT_TYPE = 5 AND proc.RDB$DEPENDED_ON_TYPE = 14", triggerName);
try (ResultSet sequenceRs = SqlUtils.executeQuery(conn, sql)) {
if (sequenceRs.next()) {
String sequenceName = sequenceRs.getString(1).trim();
defaultValue = "NEXTVAL(" + // TODO: score sequence name could be spoiled here because of name limitation
sequenceName.replace(g.getName() + "_", "") + ")";
}
}
}
} else {
defaultValue = defaultSource.replace("default", "").trim();
if (BooleanColumn.class.equals(dbColumnInfo.getType())) {
defaultValue = "0".equals(defaultValue) ? "'FALSE'" : "'TRUE'";
} else if (DateTimeColumn.class.equals(dbColumnInfo.getType())) {
if (FireBirdConstants.CURRENT_TIMESTAMP.equalsIgnoreCase(defaultValue)) {
defaultValue = "GETDATE()";
} else {
Matcher m = DATE_PATTERN.matcher(defaultValue);
if (m.find()) {
defaultValue = String.format("'%s%s%s'", m.group(3), m.group(2), m.group(1));
}
}
} else if (BinaryColumn.class.equals(dbColumnInfo.getType())) {
Matcher m = HEX_STRING.matcher(defaultValue);
if (m.find()) {
defaultValue = "0x" + m.group(1);
}
}
}
}
if (defaultValue != null) {
dbColumnInfo.setDefaultValue(defaultValue);
}
}
use of ru.curs.celesta.score.Grain in project celesta by CourseOrchestra.
the class OraAdaptor method processDefaults.
private void processDefaults(Connection conn, Column<?> c, DbColumnInfo result) throws SQLException {
ResultSet rs;
TableElement te = c.getParentTable();
Grain g = te.getGrain();
PreparedStatement getDefault = conn.prepareStatement(String.format("select DATA_DEFAULT from DBA_TAB_COLUMNS where " + "owner = sys_context('userenv','session_user') " + "and TABLE_NAME = '%s_%s' and COLUMN_NAME = '%s'", g.getName(), te.getName(), c.getName()));
try {
rs = getDefault.executeQuery();
if (!rs.next()) {
return;
}
String body = rs.getString(1);
if (body == null || "null".equalsIgnoreCase(body)) {
if (c instanceof IntegerColumn) {
IntegerColumn ic = (IntegerColumn) c;
String sequenceTriggerName = generateSequenceTriggerName(ic);
String sql = String.format("SELECT REFERENCED_NAME FROM USER_DEPENDENCIES " + " WHERE NAME = '%s' " + " AND TYPE = 'TRIGGER' " + " AND REFERENCED_TYPE = 'SEQUENCE'", sequenceTriggerName);
try (Statement stmt = conn.createStatement();
ResultSet sequenceRs = stmt.executeQuery(sql)) {
if (sequenceRs.next()) {
String sequenceName = sequenceRs.getString(1);
body = "NEXTVAL(" + sequenceName.replace(g.getName() + "_", "") + ")";
} else {
return;
}
}
} else {
return;
}
}
if (BooleanColumn.class == result.getType()) {
body = "0".equals(body.trim()) ? "'FALSE'" : "'TRUE'";
} else if (DateTimeColumn.class == result.getType()) {
if (body.toLowerCase().contains("sysdate")) {
body = "GETDATE()";
} else {
Matcher m = DATE_PATTERN.matcher(body);
if (m.find()) {
body = String.format("'%s%s%s'", m.group(1), m.group(2), m.group(3));
}
}
} else if (BinaryColumn.class == result.getType()) {
Matcher m = HEX_STRING.matcher(body);
if (m.find()) {
body = "0x" + m.group(1);
}
} else {
body = body.trim();
}
result.setDefaultValue(body);
} finally {
getDefault.close();
}
}
use of ru.curs.celesta.score.Grain in project celesta by CourseOrchestra.
the class CursorGenerator method calcSourcePackage.
static String calcSourcePackage(GrainElement ge, String scorePath) {
String result;
Grain g = ge.getGrain();
if (g.getName().equals(g.getScore().getSysSchemaName())) {
result = "ru.curs.celesta.syscursors";
} else {
String grainPartRelativePath = new FileResource(new File(scorePath)).getRelativePath(ge.getGrainPart().getSource());
result = Optional.of(grainPartRelativePath.lastIndexOf(File.separatorChar)).filter(i -> i >= 0).map(i -> grainPartRelativePath.substring(0, i).replace(File.separator, ".")).orElse("");
if (result.startsWith(".")) {
result = result.substring(1);
}
}
return result;
}
use of ru.curs.celesta.score.Grain in project celesta by CourseOrchestra.
the class AbstractAdaptorTest method testCreateAndAlterSequence.
@Test
void testCreateAndAlterSequence() throws Exception {
Grain g = score.getGrain(GRAIN_NAME);
SequenceElement sequence = g.getElement("testSequence", SequenceElement.class);
if (dba.sequenceExists(conn, g.getName(), sequence.getName()))
dba.dropSequence(conn, sequence);
// Sequence not exists
assertFalse(dba.sequenceExists(conn, g.getName(), sequence.getName()));
dba.createSequence(conn, sequence);
assertTrue(dba.sequenceExists(conn, g.getName(), sequence.getName()));
DbSequenceInfo sequenceInfo = dba.getSequenceInfo(conn, sequence);
assertFalse(sequenceInfo.reflects(sequence));
assertAll(() -> assertEquals(1L, sequenceInfo.getIncrementBy()), () -> assertEquals(5L, sequenceInfo.getMinValue()), () -> assertEquals(Long.MAX_VALUE, sequenceInfo.getMaxValue()), () -> assertEquals(false, sequenceInfo.isCycle()));
assertEquals(5, dba.nextSequenceValue(conn, sequence));
assertEquals(6, dba.nextSequenceValue(conn, sequence));
// Modifying of increment by
sequence.getArguments().put(SequenceElement.Argument.INCREMENT_BY, 2L);
assertTrue(sequenceInfo.reflects(sequence));
dba.alterSequence(conn, sequence);
DbSequenceInfo sequenceInfo2 = dba.getSequenceInfo(conn, sequence);
assertFalse(sequenceInfo2.reflects(sequence));
assertAll(() -> assertEquals(2L, sequenceInfo2.getIncrementBy()), () -> assertEquals(5L, sequenceInfo2.getMinValue()), () -> assertEquals(Long.MAX_VALUE, sequenceInfo2.getMaxValue()), () -> assertEquals(false, sequenceInfo2.isCycle()));
// Altering to short cycle
sequence.getArguments().put(SequenceElement.Argument.INCREMENT_BY, 1L);
sequence.getArguments().put(SequenceElement.Argument.MINVALUE, 5L);
sequence.getArguments().put(SequenceElement.Argument.MAXVALUE, 7L);
sequence.getArguments().put(SequenceElement.Argument.CYCLE, true);
assertTrue(sequenceInfo.reflects(sequence));
dba.alterSequence(conn, sequence);
DbSequenceInfo sequenceInfo3 = dba.getSequenceInfo(conn, sequence);
assertFalse(sequenceInfo3.reflects(sequence));
assertAll(() -> assertEquals(1L, sequenceInfo3.getIncrementBy()), () -> assertEquals(5L, sequenceInfo3.getMinValue()), () -> assertEquals(7L, sequenceInfo3.getMaxValue()), () -> assertEquals(true, sequenceInfo3.isCycle()));
dba.dropSequence(conn, sequence);
}
Aggregations