( table: any, fieldOptions: FieldOptions, )
| 8 | |
| 9 | /** Add a model field to a table schema. */ |
| 10 | export function addFieldToSchema( |
| 11 | table: any, |
| 12 | fieldOptions: FieldOptions, |
| 13 | ) { |
| 14 | const type = typeof fieldOptions.type === "string" |
| 15 | ? fieldOptions.type |
| 16 | : fieldOptions.type.type!; |
| 17 | |
| 18 | let instruction; |
| 19 | |
| 20 | if (typeof fieldOptions.type === "object") { |
| 21 | if (fieldOptions.type.relationship) { |
| 22 | const relationshipPKName = fieldOptions.type.relationship.model |
| 23 | .getComputedPrimaryKey(); |
| 24 | |
| 25 | const relationshipPKProps: FieldProps = fieldOptions.type.relationship |
| 26 | .model |
| 27 | .getComputedPrimaryProps(); |
| 28 | |
| 29 | const relationshipPKType: FieldTypeString = fieldOptions.type.relationship |
| 30 | .model |
| 31 | .getComputedPrimaryType(); |
| 32 | |
| 33 | if (relationshipPKType === "integer" || relationshipPKType === "bigInteger") { |
| 34 | const foreignField = table[relationshipPKType](fieldOptions.name); |
| 35 | |
| 36 | if (!relationshipPKProps.allowNull) { |
| 37 | foreignField.notNullable(); |
| 38 | } |
| 39 | |
| 40 | if (relationshipPKProps.autoIncrement) { |
| 41 | foreignField.unsigned(); |
| 42 | } |
| 43 | } else { |
| 44 | table[relationshipPKType](fieldOptions.name); |
| 45 | } |
| 46 | |
| 47 | table |
| 48 | .foreign(fieldOptions.name) |
| 49 | .references( |
| 50 | fieldOptions.type.relationship.model |
| 51 | .field(relationshipPKName), |
| 52 | ) |
| 53 | .onDelete("CASCADE"); |
| 54 | |
| 55 | return; |
| 56 | } |
| 57 | |
| 58 | const fieldNameArgs: [string | number | (string | number)[]] = [ |
| 59 | fieldOptions.name, |
| 60 | ]; |
| 61 | |
| 62 | if (fieldOptions.type.length) { |
| 63 | fieldNameArgs.push(fieldOptions.type.length); |
| 64 | } |
| 65 | |
| 66 | if (fieldOptions.type.precision) { |
| 67 | fieldNameArgs.push(fieldOptions.type.precision); |
no test coverage detected