public static long insert(Realm realm, some.test.Simple object, Map<RealmModel,Long> cache) { if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { return ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex(); } Table table = realm.getTable(some.test.Simple.class); long tableNativePtr = table.getNativePtr(); SimpleColumnInfo columnInfo = (SimpleColumnInfo) realm.getSchema().getColumnInfo(some.test.Simple.class); long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); String realmGet$name = ((SimpleRealmProxyInterface) object).realmGet$name(); if (realmGet$name != null) { Table.nativeSetString(tableNativePtr, columnInfo.nameIndex, rowIndex, realmGet$name, false); } Table.nativeSetLong(tableNativePtr, columnInfo.ageIndex, rowIndex, ((SimpleRealmProxyInterface) object).realmGet$age(), false); return rowIndex; }
public static void insert(Realm realm, Iterator<? extends RealmModel> objects, Map<RealmModel,Long> cache) { Table table = realm.getTable(some.test.Simple.class); long tableNativePtr = table.getNativePtr(); SimpleColumnInfo columnInfo = (SimpleColumnInfo) realm.getSchema().getColumnInfo(some.test.Simple.class); some.test.Simple object = null; while (objects.hasNext()) { object = (some.test.Simple) objects.next(); if (cache.containsKey(object)) { continue; } if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { cache.put(object, ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex()); continue; } long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); String realmGet$name = ((SimpleRealmProxyInterface) object).realmGet$name(); if (realmGet$name != null) { Table.nativeSetString(tableNativePtr, columnInfo.nameIndex, rowIndex, realmGet$name, false); } Table.nativeSetLong(tableNativePtr, columnInfo.ageIndex, rowIndex, ((SimpleRealmProxyInterface) object).realmGet$age(), false); } }
public static long insertOrUpdate(Realm realm, some.test.Simple object, Map<RealmModel,Long> cache) { if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { return ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex(); } Table table = realm.getTable(some.test.Simple.class); long tableNativePtr = table.getNativePtr(); SimpleColumnInfo columnInfo = (SimpleColumnInfo) realm.getSchema().getColumnInfo(some.test.Simple.class); long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); String realmGet$name = ((SimpleRealmProxyInterface) object).realmGet$name(); if (realmGet$name != null) { Table.nativeSetString(tableNativePtr, columnInfo.nameIndex, rowIndex, realmGet$name, false); } else { Table.nativeSetNull(tableNativePtr, columnInfo.nameIndex, rowIndex, false); } Table.nativeSetLong(tableNativePtr, columnInfo.ageIndex, rowIndex, ((SimpleRealmProxyInterface) object).realmGet$age(), false); return rowIndex; }
public static void insertOrUpdate(Realm realm, Iterator<? extends RealmModel> objects, Map<RealmModel,Long> cache) { Table table = realm.getTable(some.test.Simple.class); long tableNativePtr = table.getNativePtr(); SimpleColumnInfo columnInfo = (SimpleColumnInfo) realm.getSchema().getColumnInfo(some.test.Simple.class); some.test.Simple object = null; while (objects.hasNext()) { object = (some.test.Simple) objects.next(); if (cache.containsKey(object)) { continue; } if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { cache.put(object, ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex()); continue; } long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); String realmGet$name = ((SimpleRealmProxyInterface) object).realmGet$name(); if (realmGet$name != null) { Table.nativeSetString(tableNativePtr, columnInfo.nameIndex, rowIndex, realmGet$name, false); } else { Table.nativeSetNull(tableNativePtr, columnInfo.nameIndex, rowIndex, false); } Table.nativeSetLong(tableNativePtr, columnInfo.ageIndex, rowIndex, ((SimpleRealmProxyInterface) object).realmGet$age(), false); } }
public static void insert(Realm realm, Iterator<? extends RealmModel> objects, Map<RealmModel,Long> cache) { Table table = realm.getTable(some.test.Booleans.class); long tableNativePtr = table.getNativePtr(); BooleansColumnInfo columnInfo = (BooleansColumnInfo) realm.getSchema().getColumnInfo(some.test.Booleans.class); some.test.Booleans object = null; while (objects.hasNext()) { object = (some.test.Booleans) objects.next(); if (cache.containsKey(object)) { continue; } if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { cache.put(object, ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex()); continue; } long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); Table.nativeSetBoolean(tableNativePtr, columnInfo.doneIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$done(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.isReadyIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$isReady(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.mCompletedIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$mCompleted(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.anotherBooleanIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$anotherBoolean(), false); } }
public static void insertOrUpdate(Realm realm, Iterator<? extends RealmModel> objects, Map<RealmModel,Long> cache) { Table table = realm.getTable(some.test.Booleans.class); long tableNativePtr = table.getNativePtr(); BooleansColumnInfo columnInfo = (BooleansColumnInfo) realm.getSchema().getColumnInfo(some.test.Booleans.class); some.test.Booleans object = null; while (objects.hasNext()) { object = (some.test.Booleans) objects.next(); if (cache.containsKey(object)) { continue; } if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { cache.put(object, ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex()); continue; } long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); Table.nativeSetBoolean(tableNativePtr, columnInfo.doneIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$done(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.isReadyIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$isReady(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.mCompletedIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$mCompleted(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.anotherBooleanIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$anotherBoolean(), false); } }
<E extends RealmModel> E get(@Nullable Class<E> clazz, @Nullable String dynamicClassName, long rowIndex) { final boolean isDynamicRealmObject = dynamicClassName != null; // 'clazz' is non-null when 'dynamicClassName' is null. //noinspection ConstantConditions final Table table = isDynamicRealmObject ? getSchema().getTable(dynamicClassName) : getSchema().getTable(clazz); E result; if (isDynamicRealmObject) { @SuppressWarnings("unchecked") E dynamicObj = (E) new DynamicRealmObject(this, (rowIndex != Table.NO_MATCH) ? table.getCheckedRow(rowIndex) : InvalidRow.INSTANCE); result = dynamicObj; } else { result = configuration.getSchemaMediator().newInstance(clazz, this, (rowIndex != Table.NO_MATCH) ? table.getUncheckedRow(rowIndex) : InvalidRow.INSTANCE, getSchema().getColumnInfo(clazz), false, Collections.<String>emptyList()); } return result; }
/** * The constructor is private to enforce the use of the static one. * * @param cache the {@link RealmCache} associated to this Realm instance. * @throws IllegalArgumentException if trying to open an encrypted Realm with the wrong key. */ private Realm(RealmCache cache) { super(cache, createExpectedSchemaInfo(cache.getConfiguration().getSchemaMediator())); schema = new ImmutableRealmSchema(this, new ColumnIndices(configuration.getSchemaMediator(), sharedRealm.getSchemaInfo())); // FIXME: This is to work around the different behaviour between the read only Realms in the Object Store and // in current java implementation. Opening a read only Realm with some missing schemas is allowed by Object // Store and realm-cocoa. In that case, any query based on the missing schema should just return an empty // results. Fix this together with https://github.com/realm/realm-java/issues/2953 if (configuration.isReadOnly()) { RealmProxyMediator mediator = configuration.getSchemaMediator(); Set<Class<? extends RealmModel>> classes = mediator.getModelClasses(); for (Class<? extends RealmModel> clazz : classes) { String tableName = Table.getTableNameForClass(mediator.getSimpleClassName(clazz)); if (!sharedRealm.hasTable(tableName)) { sharedRealm.close(); throw new RealmMigrationNeededException(configuration.getPath(), String.format(Locale.US, "Cannot open the read only Realm. '%s' is missing.", Table.getClassNameForTable(tableName))); } } } }
/** * Same as {@link #createObject(Class)} but this does not check the thread. * * @param clazz the Class of the object to create. * @param acceptDefaultValue if {@code true}, default value of the object will be applied and * if {@code false}, it will be ignored. * @return the new object. * @throws RealmException if the primary key is defined in the model class or an object cannot be created. */ // Called from proxy classes. <E extends RealmModel> E createObjectInternal( Class<E> clazz, boolean acceptDefaultValue, List<String> excludeFields) { Table table = schema.getTable(clazz); // Checks and throws the exception earlier for a better exception message. if (OsObjectStore.getPrimaryKeyForObject( sharedRealm, configuration.getSchemaMediator().getSimpleClassName(clazz)) != null) { throw new RealmException(String.format(Locale.US, "'%s' has a primary key, use" + " 'createObject(Class<E>, Object)' instead.", table.getClassName())); } return configuration.getSchemaMediator().newInstance(clazz, this, OsObject.create(table), schema.getColumnInfo(clazz), acceptDefaultValue, excludeFields); }
/** * Sets a reference to another object on the given field. * * @param fieldName field name. * @param value object to link to. * @throws IllegalArgumentException if field name doesn't exist, it doesn't link to other Realm objects, the type * of DynamicRealmObject doesn't match or it belongs to a different Realm. */ public void setObject(String fieldName, @Nullable DynamicRealmObject value) { proxyState.getRealm$realm().checkIfValid(); long columnIndex = proxyState.getRow$realm().getColumnIndex(fieldName); if (value == null) { proxyState.getRow$realm().nullifyLink(columnIndex); } else { if (value.proxyState.getRealm$realm() == null || value.proxyState.getRow$realm() == null) { throw new IllegalArgumentException("Cannot link to objects that are not part of the Realm."); } if (proxyState.getRealm$realm() != value.proxyState.getRealm$realm()) { throw new IllegalArgumentException("Cannot add an object from another Realm instance."); } Table table = proxyState.getRow$realm().getTable().getLinkTarget(columnIndex); Table inputTable = value.proxyState.getRow$realm().getTable(); if (!table.hasSameSchema(inputTable)) { throw new IllegalArgumentException(String.format(Locale.US, "Type of object is wrong. Was %s, expected %s", inputTable.getName(), table.getName())); } proxyState.getRow$realm().setLink(columnIndex, value.proxyState.getRow$realm().getIndex()); } }
Table getTable(Class<? extends RealmModel> clazz) { Table table = classToTable.get(clazz); if (table != null) { return table; } Class<? extends RealmModel> originalClass = Util.getOriginalModelClass(clazz); if (isProxyClass(originalClass, clazz)) { // If passed 'clazz' is the proxy, try again with model class. table = classToTable.get(originalClass); } if (table == null) { String tableName = Table.getTableNameForClass( realm.getConfiguration().getSchemaMediator().getSimpleClassName(originalClass)); table = realm.getSharedRealm().getTable(tableName); classToTable.put(originalClass, table); } if (isProxyClass(originalClass, clazz)) { // 'clazz' is the proxy class for 'originalClass'. classToTable.put(clazz, table); } return table; }
RealmObjectSchema getSchemaForClass(Class<? extends RealmModel> clazz) { RealmObjectSchema classSchema = classToSchema.get(clazz); if (classSchema != null) { return classSchema; } Class<? extends RealmModel> originalClass = Util.getOriginalModelClass(clazz); if (isProxyClass(originalClass, clazz)) { // If passed 'clazz' is the proxy, try again with model class. classSchema = classToSchema.get(originalClass); } if (classSchema == null) { Table table = getTable(clazz); classSchema = new ImmutableRealmObjectSchema(realm, this, table, getColumnInfo(originalClass)); classToSchema.put(originalClass, classSchema); } if (isProxyClass(originalClass, clazz)) { // 'clazz' is the proxy class for 'originalClass'. classToSchema.put(clazz, classSchema); } return classSchema; }
@Test public void setGetClassName() { final String[] validClassNames = { TestHelper.getRandomString(1), "Darby", TestHelper.getRandomString(Table.CLASS_NAME_MAX_LENGTH) }; if (type == ObjectSchemaType.IMMUTABLE) { thrown.expect(UnsupportedOperationException.class); DOG_SCHEMA.setClassName(validClassNames[0]); return; } assertEquals("Dog", DOG_SCHEMA.getClassName()); for (String validClassName : validClassNames) { DOG_SCHEMA.setClassName(validClassName); assertEquals(validClassName, DOG_SCHEMA.getClassName()); assertTrue(realmSchema.contains(validClassName)); } }
@Test public void index() { Table table = realm.getTable(AnnotationIndexTypes.class); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexString"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexString"))); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexInt"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexInt"))); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexByte"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexByte"))); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexShort"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexShort"))); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexLong"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexLong"))); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexBoolean"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexBoolean"))); assertTrue(table.hasSearchIndex(table.getColumnIndex("indexDate"))); assertFalse(table.hasSearchIndex(table.getColumnIndex("notIndexDate"))); }
public static Table createTable(OsSharedRealm sharedRealm, String name, AdditionalTableSetup additionalSetup) { boolean wasInTransaction = sharedRealm.isInTransaction(); if (!wasInTransaction) { sharedRealm.beginTransaction(); } try { Table table = sharedRealm.createTable(name); if (additionalSetup != null) { additionalSetup.execute(table); } return table; } catch (RuntimeException e) { if (!wasInTransaction) { sharedRealm.cancelTransaction(); } throw e; } finally { if (!wasInTransaction && sharedRealm.isInTransaction()) { sharedRealm.commitTransaction(); } } }
@Test public void create() { final String[] validClassNames = { TestHelper.getRandomString(1), "Darby", TestHelper.getRandomString(Table.CLASS_NAME_MAX_LENGTH) }; if (type == SchemaType.IMMUTABLE) { thrown.expect(UnsupportedOperationException.class); realmSchema.create(validClassNames[0]); return; } for (String validClassName : validClassNames) { realmSchema.create(validClassName); assertTrue(realmSchema.contains(validClassName)); } }
@Test public void createWithPrimaryKeyField_invalidClassNameThrows() { if (type == SchemaType.IMMUTABLE) { return; } String[] invalidNames = { null, "", TestHelper.getRandomString(Table.CLASS_NAME_MAX_LENGTH + 1) }; for (String name : invalidNames) { try { realmSchema.createWithPrimaryKeyField(name, "pkField", int.class); fail(); } catch (IllegalArgumentException ignored) { } assertFalse(String.format("'%s' failed", name), realmSchema.contains(name)); } }
@Test public void setter_binary_long_values() { byte[] longBinary = new byte[Table.MAX_BINARY_SIZE]; byte[] tooLongBinary = new byte[Table.MAX_BINARY_SIZE + 1]; realm.beginTransaction(); AllTypes allTypes = realm.createObject(AllTypes.class); allTypes.setColumnBinary(longBinary); realm.commitTransaction(); assertEquals(longBinary.length, allTypes.getColumnBinary().length); realm.beginTransaction(); try { allTypes.setColumnBinary(tooLongBinary); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), CoreMatchers.containsString("which exceeds the max binary size")); } }
@Test public void setter_string_long_values() { byte[] tooLongBinary = new byte[Table.MAX_STRING_SIZE + 1]; Arrays.fill(tooLongBinary, (byte) 'a'); String longString = new String(tooLongBinary, 0, Table.MAX_STRING_SIZE, Charset.forName("US-ASCII")); String tooLongString = new String(tooLongBinary, 0, Table.MAX_STRING_SIZE + 1, Charset.forName("US-ASCII")); realm.beginTransaction(); AllTypes allTypes = realm.createObject(AllTypes.class); allTypes.setColumnString(longString); realm.commitTransaction(); assertEquals(longString.length(), allTypes.getColumnString().length()); realm.beginTransaction(); try { allTypes.setColumnString(tooLongString); fail(); } catch (IllegalArgumentException expected) { assertThat(expected.getMessage(), CoreMatchers.containsString("which exceeds the max string length")); } }
public <T> T executeSQL(String databaseId, String query, ExecuteResultHandler<T> executeResultHandler) { final SharedGroup group = openSharedGroupForImplicitTransactions(databaseId); //noinspection TryWithIdenticalCatches,TryFinallyCanBeTryWithResources try { final ImplicitTransaction transaction = group.beginImplicitTransaction(); query = query.trim(); final Matcher selectMatcher = SELECT_PATTERN.matcher(query); if (selectMatcher.matches()) { final String tableName = selectMatcher.group(1); final Table table = transaction.getTable(tableName); return executeResultHandler.handleSelect(table, true); } // TODO 読み出し以外にも対応する return null; } finally { group.close(); } }
public static long insert(Realm realm, some.test.Booleans object, Map<RealmModel,Long> cache) { if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { return ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex(); } Table table = realm.getTable(some.test.Booleans.class); long tableNativePtr = table.getNativePtr(); BooleansColumnInfo columnInfo = (BooleansColumnInfo) realm.getSchema().getColumnInfo(some.test.Booleans.class); long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); Table.nativeSetBoolean(tableNativePtr, columnInfo.doneIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$done(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.isReadyIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$isReady(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.mCompletedIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$mCompleted(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.anotherBooleanIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$anotherBoolean(), false); return rowIndex; }
public static long insertOrUpdate(Realm realm, some.test.Booleans object, Map<RealmModel,Long> cache) { if (object instanceof RealmObjectProxy && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm() != null && ((RealmObjectProxy) object).realmGet$proxyState().getRealm$realm().getPath().equals(realm.getPath())) { return ((RealmObjectProxy) object).realmGet$proxyState().getRow$realm().getIndex(); } Table table = realm.getTable(some.test.Booleans.class); long tableNativePtr = table.getNativePtr(); BooleansColumnInfo columnInfo = (BooleansColumnInfo) realm.getSchema().getColumnInfo(some.test.Booleans.class); long rowIndex = OsObject.createRow(table); cache.put(object, rowIndex); Table.nativeSetBoolean(tableNativePtr, columnInfo.doneIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$done(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.isReadyIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$isReady(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.mCompletedIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$mCompleted(), false); Table.nativeSetBoolean(tableNativePtr, columnInfo.anotherBooleanIndex, rowIndex, ((BooleansRealmProxyInterface) object).realmGet$anotherBoolean(), false); return rowIndex; }
@Override public RealmObjectSchema get(String className) { checkNotEmpty(className, EMPTY_STRING_MSG); String internalClassName = Table.getTableNameForClass(className); if (!realm.getSharedRealm().hasTable(internalClassName)) { return null; } Table table = realm.getSharedRealm().getTable(internalClassName); return new ImmutableRealmObjectSchema(realm, this, table, getColumnInfo(className)); }
/** * Instantiates and adds a new object to the Realm. * * @param className the class name of the object to create. * @return the new object. * @throws RealmException if the object could not be created. */ public DynamicRealmObject createObject(String className) { checkIfValid(); Table table = schema.getTable(className); String pkField = OsObjectStore.getPrimaryKeyForObject(sharedRealm, className); // Check and throw the exception earlier for a better exception message. if (pkField != null) { throw new RealmException(String.format(Locale.US, "'%s' has a primary key field '%s', use 'createObject(String, Object)' instead.", className, pkField)); } return new DynamicRealmObject(this, CheckedRow.getFromRow(OsObject.create(table))); }
@Override public RealmObjectSchema get(String className) { checkNotEmpty(className, EMPTY_STRING_MSG); String internalClassName = Table.getTableNameForClass(className); if (!realm.getSharedRealm().hasTable(internalClassName)) { return null; } Table table = realm.getSharedRealm().getTable(internalClassName); return new MutableRealmObjectSchema(realm, this, table); }
@Override public RealmObjectSchema create(String className) { // Adding a class is always permitted. checkNotEmpty(className, EMPTY_STRING_MSG); String internalTableName = Table.getTableNameForClass(className); if (className.length() > Table.CLASS_NAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format(Locale.US, "Class name is too long. Limit is %1$d characters: %2$s", Table.CLASS_NAME_MAX_LENGTH, className.length())); } return new MutableRealmObjectSchema(realm, this, realm.getSharedRealm().createTable(internalTableName)); }
@Override public void remove(String className) { realm.checkNotInSync(); // Destructive modifications are not permitted. checkNotEmpty(className, EMPTY_STRING_MSG); String internalTableName = Table.getTableNameForClass(className); if (!OsObjectStore.deleteTableForObject(realm.getSharedRealm(), className)) { throw new IllegalArgumentException("Cannot remove class because it is not in this Realm: " + className); } removeFromClassNameToSchemaMap(internalTableName); }
@Override public RealmObjectSchema rename(String oldClassName, String newClassName) { realm.checkNotInSync(); // Destructive modifications are not permitted. checkNotEmpty(oldClassName, "Class names cannot be empty or null"); checkNotEmpty(newClassName, "Class names cannot be empty or null"); String oldInternalName = Table.getTableNameForClass(oldClassName); String newInternalName = Table.getTableNameForClass(newClassName); checkHasTable(oldClassName, "Cannot rename class because it doesn't exist in this Realm: " + oldClassName); if (realm.getSharedRealm().hasTable(newInternalName)) { throw new IllegalArgumentException(oldClassName + " cannot be renamed because the new class already exists: " + newClassName); } // Checks if there is a primary key defined for the old class. String pkField = OsObjectStore.getPrimaryKeyForObject(realm.sharedRealm, oldClassName); if (pkField != null) { OsObjectStore.setPrimaryKeyForObject(realm.sharedRealm, oldClassName, null); } realm.getSharedRealm().renameTable(oldInternalName, newInternalName); Table table = realm.getSharedRealm().getTable(newInternalName); // Sets the primary key for the new class if necessary. if (pkField != null) { OsObjectStore.setPrimaryKeyForObject(realm.sharedRealm, newClassName, pkField); } RealmObjectSchema objectSchema = removeFromClassNameToSchemaMap(oldInternalName); if (objectSchema == null || !objectSchema.getTable().isValid() || !objectSchema.getClassName().equals(newClassName)) { objectSchema = new MutableRealmObjectSchema(realm, this, table); } putToClassNameToSchemaMap(newInternalName, objectSchema); return objectSchema; }
private String checkAndGetTableNameFromClassName(String className) { if (className.length() > Table.CLASS_NAME_MAX_LENGTH) { throw new IllegalArgumentException( String.format(Locale.US, "Class name is too long. Limit is %1$d characters: %2$s", Table.CLASS_NAME_MAX_LENGTH, className.length())); } return Table.getTableNameForClass(className); }
@Override public RealmObjectSchema setClassName(String className) { realm.checkNotInSync(); // renaming a table is not permitted checkEmpty(className); String internalTableName = Table.getTableNameForClass(className); if (className.length() > Table.CLASS_NAME_MAX_LENGTH) { throw new IllegalArgumentException(String.format(Locale.US, "Class name is too long. Limit is %1$d characters: \'%2$s\' (%3$d)", Table.CLASS_NAME_MAX_LENGTH, className, className.length())); } //noinspection ConstantConditions if (realm.sharedRealm.hasTable(internalTableName)) { throw new IllegalArgumentException("Class already exists: " + className); } // in case this table has a primary key, we need to transfer it after renaming the table. //noinspection ConstantConditions @Nonnull String oldTableName = table.getName(); @Nonnull String oldClassName = table.getClassName(); String pkField = OsObjectStore.getPrimaryKeyForObject(realm.sharedRealm, oldClassName); if (pkField != null) { OsObjectStore.setPrimaryKeyForObject(realm.sharedRealm, oldClassName, null); } realm.sharedRealm.renameTable(oldTableName, internalTableName); if (pkField != null) { try { OsObjectStore.setPrimaryKeyForObject(realm.sharedRealm, className, pkField); } catch (Exception e) { // revert the table name back when something goes wrong //noinspection ConstantConditions realm.sharedRealm.renameTable(table.getName(), oldTableName); throw e; } } return this; }
@Override public RealmObjectSchema addRealmObjectField(String fieldName, RealmObjectSchema objectSchema) { checkLegalName(fieldName); checkFieldNameIsAvailable(fieldName); table.addColumnLink(RealmFieldType.OBJECT, fieldName, realm.sharedRealm.getTable(Table.getTableNameForClass(objectSchema.getClassName()))); return this; }
@Override public RealmObjectSchema addRealmListField(String fieldName, RealmObjectSchema objectSchema) { checkLegalName(fieldName); checkFieldNameIsAvailable(fieldName); table.addColumnLink(RealmFieldType.LIST, fieldName, realm.sharedRealm.getTable(Table.getTableNameForClass(objectSchema.getClassName()))); return this; }
@SuppressLint("unused") static <T extends RealmModel> RealmResults<T> createBacklinkResults(BaseRealm realm, Row row, Class<T> srcTableType, String srcFieldName) { UncheckedRow uncheckedRow = (UncheckedRow) row; Table srcTable = realm.getSchema().getTable(srcTableType); return new RealmResults<>( realm, OsResults.createForBacklinks(realm.sharedRealm, uncheckedRow, srcTable, srcFieldName), srcTableType); }
static RealmResults<DynamicRealmObject> createDynamicBacklinkResults(DynamicRealm realm, CheckedRow row, Table srcTable, String srcFieldName) { final String srcClassName = Table.getClassNameForTable(srcTable.getName()); //noinspection ConstantConditions return new RealmResults<>( realm, OsResults.createForBacklinks(realm.sharedRealm, row, srcTable, srcFieldName), srcClassName); }
/** * Same as {@link #createObject(Class, Object)} but this does not check the thread. * * @param clazz the Class of the object to create. * @param primaryKeyValue value for the primary key field. * @param acceptDefaultValue if {@code true}, default value of the object will be applied and * if {@code false}, it will be ignored. * @return the new object. * @throws RealmException if object could not be created due to the primary key being invalid. * @throws IllegalStateException if the model class does not have an primary key defined. * @throws IllegalArgumentException if the {@code primaryKeyValue} doesn't have a value that can be converted to the * expected value. */ // Called from proxy classes. <E extends RealmModel> E createObjectInternal( Class<E> clazz, @Nullable Object primaryKeyValue, boolean acceptDefaultValue, List<String> excludeFields) { Table table = schema.getTable(clazz); return configuration.getSchemaMediator().newInstance(clazz, this, OsObject.createWithPrimaryKey(table, primaryKeyValue), schema.getColumnInfo(clazz), acceptDefaultValue, excludeFields); }
private void setValue(@Nullable Long value, boolean isDefault) { Row row = getRow(); Table table = row.getTable(); long rowIndex = row.getIndex(); long columnIndex = getColumnIndex(); if (value == null) { table.setNull(columnIndex, rowIndex, isDefault); } else { table.setLong(columnIndex, rowIndex, value, isDefault); } }
@Override protected void compileFieldDescription(List<String> fields) { final int nFields = fields.size(); long[] columnIndices = new long[nFields]; Table currentTable = table; String currentClassName = null; String currentColumnName = null; RealmFieldType currentColumnType = null; for (int i = 0; i < nFields; i++) { currentColumnName = fields.get(i); if ((currentColumnName == null) || (currentColumnName.length() <= 0)) { throw new IllegalArgumentException( "Invalid query: Field descriptor contains an empty field. A field description may not begin with or contain adjacent periods ('.')."); } currentClassName = currentTable.getClassName(); final long columnIndex = currentTable.getColumnIndex(currentColumnName); if (columnIndex < 0) { throw new IllegalArgumentException( String.format(Locale.US, "Invalid query: field '%s' not found in table '%s'.", currentColumnName, currentClassName)); } currentColumnType = currentTable.getColumnType(columnIndex); if (i < nFields - 1) { verifyInternalColumnType(currentClassName, currentColumnName, currentColumnType); currentTable = currentTable.getLinkTarget(columnIndex); } columnIndices[i] = columnIndex; } setCompilationResults(currentClassName, currentColumnName, currentColumnType, columnIndices, new long[nFields]); }
/** * Returns the {@link RealmObjectSchema}s for all RealmObject classes that can be saved in this Realm. If this * {@link RealmSchema} is immutable, an immutable {@link RealmObjectSchema} set will be returned. Otherwise, it * returns an mutable {@link RealmObjectSchema} set. * * @return the set of all classes in this Realm or no RealmObject classes can be saved in the Realm. */ public Set<RealmObjectSchema> getAll() { int tableCount = (int) realm.getSharedRealm().size(); Set<RealmObjectSchema> schemas = new LinkedHashSet<>(tableCount); for (int i = 0; i < tableCount; i++) { RealmObjectSchema objectSchema = get(Table.getClassNameForTable(realm.getSharedRealm().getTableName(i))); if (objectSchema != null) { schemas.add(objectSchema); } } return schemas; }
Table getTable(String className) { String tableName = Table.getTableNameForClass(className); Table table = dynamicClassToTable.get(tableName); if (table != null) { return table; } table = realm.getSharedRealm().getTable(tableName); dynamicClassToTable.put(tableName, table); return table; }
RealmObjectSchema getSchemaForClass(String className) { String tableName = Table.getTableNameForClass(className); RealmObjectSchema dynamicSchema = dynamicClassToSchema.get(tableName); if (dynamicSchema == null || !dynamicSchema.getTable().isValid() || !dynamicSchema.getClassName().equals(className)) { if (!realm.getSharedRealm().hasTable(tableName)) { throw new IllegalArgumentException("The class " + className + " doesn't exist in this Realm."); } dynamicSchema = new ImmutableRealmObjectSchema(realm, this, realm.getSharedRealm().getTable(tableName)); dynamicClassToSchema.put(tableName, dynamicSchema); } return dynamicSchema; }