(model: Model)
| 33 | } |
| 34 | |
| 35 | export function getDatasource(model: Model) { |
| 36 | const datasource = model.declarations.find((d) => d.$type === 'DataSource'); |
| 37 | if (!datasource) { |
| 38 | throw new CliError('No datasource declaration found in the schema.'); |
| 39 | } |
| 40 | |
| 41 | const urlField = datasource.fields.find((f) => f.name === 'url'); |
| 42 | |
| 43 | if (!urlField) throw new CliError(`No url field found in the datasource declaration.`); |
| 44 | |
| 45 | let url = getStringLiteral(urlField.value); |
| 46 | |
| 47 | if (!url && isInvocationExpr(urlField.value)) { |
| 48 | const envName = getStringLiteral(urlField.value.args[0]?.value); |
| 49 | if (!envName) { |
| 50 | throw new CliError('The url field must be a string literal or an env().'); |
| 51 | } |
| 52 | if (!process.env[envName]) { |
| 53 | throw new CliError( |
| 54 | `Environment variable ${envName} is not set, please set it to the database connection string.`, |
| 55 | ); |
| 56 | } |
| 57 | url = process.env[envName]; |
| 58 | } |
| 59 | |
| 60 | if (!url) { |
| 61 | throw new CliError('The url field must be a string literal or an env().'); |
| 62 | } |
| 63 | |
| 64 | if (url.startsWith('file:')) { |
| 65 | url = new URL(url, `file:${model.$document!.uri.path}`).pathname; |
| 66 | if (process.platform === 'win32' && url[0] === '/') url = url.slice(1); |
| 67 | } |
| 68 | |
| 69 | const defaultSchemaField = datasource.fields.find((f) => f.name === 'defaultSchema'); |
| 70 | const defaultSchema = (defaultSchemaField && getStringLiteral(defaultSchemaField.value)) || 'public'; |
| 71 | |
| 72 | const schemasField = datasource.fields.find((f) => f.name === 'schemas'); |
| 73 | const schemas = |
| 74 | (schemasField && |
| 75 | getLiteralArray(schemasField.value) |
| 76 | ?.filter((s) => s !== undefined)) as string[] || |
| 77 | []; |
| 78 | |
| 79 | const provider = getStringLiteral( |
| 80 | datasource.fields.find((f) => f.name === 'provider')?.value, |
| 81 | ); |
| 82 | if (!provider) { |
| 83 | throw new CliError(`Datasource "${datasource.name}" is missing a "provider" field.`); |
| 84 | } |
| 85 | |
| 86 | return { |
| 87 | name: datasource.name, |
| 88 | provider: provider as DataSourceProviderType, |
| 89 | url, |
| 90 | defaultSchema, |
| 91 | schemas, |
| 92 | allSchemas: [defaultSchema, ...schemas], |
no test coverage detected