Parcourir la source

fix(core): Fix float custom field handling

Closes #1561. This change ensures that default float values in MySQL do not get rounded at all, and
also leaves other drivers alone so that spurious migrations are not created for postgres.
Michael Bromley il y a 3 ans
Parent
commit
e94730bef4

+ 2 - 2
packages/core/e2e/custom-fields.e2e-spec.ts

@@ -28,7 +28,7 @@ const customConfig = mergeConfig(testConfig(), {
             { name: 'stringWithDefault', type: 'string', defaultValue: 'hello' },
             { name: 'localeStringWithDefault', type: 'localeString', defaultValue: 'hola' },
             { name: 'intWithDefault', type: 'int', defaultValue: 5 },
-            { name: 'floatWithDefault', type: 'float', defaultValue: 5.5 },
+            { name: 'floatWithDefault', type: 'float', defaultValue: 5.5678 },
             { name: 'booleanWithDefault', type: 'boolean', defaultValue: true },
             {
                 name: 'dateTimeWithDefault',
@@ -324,7 +324,7 @@ describe('Custom fields', () => {
             stringWithDefault: 'hello',
             localeStringWithDefault: 'hola',
             intWithDefault: 5,
-            floatWithDefault: 5.5,
+            floatWithDefault: 5.5678,
             booleanWithDefault: true,
             dateTimeWithDefault: '2019-04-30T12:59:16.415Z',
             // MySQL does not support defaults on TEXT fields, which is what "simple-json" uses

+ 11 - 2
packages/core/src/entity/register-custom-entity-fields.ts

@@ -101,8 +101,17 @@ function registerCustomFieldsForEntity(
                         }
                         options.length = length;
                     }
-                    if (customField.type === 'float') {
-                        options.scale = 2;
+                    if (
+                        customField.type === 'float' &&
+                        typeof customField.defaultValue === 'number' &&
+                        (dbEngine === 'mariadb' || dbEngine === 'mysql')
+                    ) {
+                        // In the MySQL driver, a default float value will get rounded to the nearest integer.
+                        // unless you specify the precision.
+                        const defaultValueDecimalPlaces = customField.defaultValue.toString().split('.')[1];
+                        if (defaultValueDecimalPlaces) {
+                            options.precision = defaultValueDecimalPlaces.length;
+                        }
                     }
                     if (
                         customField.type === 'datetime' &&