typeorm#DataSource TypeScript Examples
The following examples show how to use
typeorm#DataSource.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From typeorm-extension with MIT License | 7 votes |
export async function setupTestDatabase() {
const options = await buildDataSourceOptions({
directory: __dirname
})
await createDatabase({
options
});
const dataSource = new DataSource(options);
await dataSource.initialize();
setDataSource(dataSource);
}
Example #2
Source File: module.ts From typeorm-extension with MIT License | 7 votes |
export async function runSeeder(
dataSource: DataSource,
seeder: SeederConstructor,
options?: SeederOptions,
) : Promise<void> {
options = options || {};
options.seeds = [seeder];
options.factoriesLoad = options.factoriesLoad ?? true;
if (
options.factoriesLoad &&
!options.factories
) {
const { factories: dataSourceFactories } = dataSource.options as DataSourceOptions & SeederOptions;
if (typeof dataSourceFactories !== 'undefined') {
options.factories = dataSourceFactories;
}
}
await prepareSeeder(options);
setDataSource(dataSource);
// eslint-disable-next-line new-cap
const clazz = new seeder();
const factoryManager = useSeederFactoryManager();
await clazz.run(dataSource, factoryManager);
}
Example #3
Source File: MigrationService.ts From context-mod with MIT License | 6 votes |
constructor(data: {
type: 'app' | 'web',
logger: Logger,
database: DataSource,
options: DatabaseMigrationOptions
}) {
this.dbLogger = data.logger.child({labels: [(data.type === 'app' ? 'App' : 'Web'), `Database`, 'Migration']}, mergeArr);
this.database = data.database;
this.options = data.options;
}
Example #4
Source File: user.ts From typeorm-extension with MIT License | 6 votes |
public async run(
dataSource: DataSource,
factoryManager?: SeederFactoryManager
) : Promise<void> {
const repository = dataSource.getRepository(User);
await repository.insert([
{firstName: 'Caleb', lastName: 'Barrows', email: '[email protected]'}
]);
// ---------------------------------------------------
const userFactory = await factoryManager.get(User);
// save 1 factory generated entity, to the database
await userFactory.save();
// save 5 factory generated entities, to the database
await userFactory.saveMany(5);
}
Example #5
Source File: module.ts From typeorm-extension with MIT License | 6 votes |
export async function runSeeders(
dataSource: DataSource,
options?: SeederOptions,
) : Promise<void> {
options = options || {};
const { seeds, factories } = dataSource.options as DataSourceOptions & SeederOptions;
if (
typeof options.seeds === 'undefined' &&
typeof seeds !== 'undefined'
) {
options.seeds = seeds;
}
if (
typeof options.factories === 'undefined' &&
typeof factories !== 'undefined'
) {
options.factories = factories;
}
const items = await prepareSeeder(options);
for (let i = 0; i < items.length; i++) {
await runSeeder(dataSource, items[i], {
factoriesLoad: false,
});
}
}
Example #6
Source File: synchronize.ts From typeorm-extension with MIT License | 6 votes |
export async function synchronizeDatabase(options: DataSourceOptions) {
const dataSource = new DataSource(options);
await dataSource.initialize();
let migrationsAmount = 0;
if (options.migrations) {
migrationsAmount = Array.isArray(options.migrations) ?
options.migrations.length :
Object.keys(options.migrations).length;
}
if (migrationsAmount > 0) {
await dataSource.runMigrations();
} else {
await dataSource.synchronize(false);
}
await dataSource.destroy();
}
Example #7
Source File: create.ts From typeorm-extension with MIT License | 6 votes |
export function createDriver(connectionOptions: DataSourceOptions) {
const fakeConnection: DataSource = {
options: {
type: connectionOptions.type,
...(driversRequireDatabaseOption.indexOf(connectionOptions.type) !== -1 ? {
database: connectionOptions.database,
} : {}),
},
} as DataSource;
const driverFactory = new DriverFactory();
return driverFactory.create(fakeConnection);
}
Example #8
Source File: util.ts From context-mod with MIT License | 6 votes |
getFullEventsById = (dataSource: DataSource, ids: string[]): SelectQueryBuilder<CMEvent> => {
let query = dataSource.getRepository(CMEvent)
.createQueryBuilder("event")
.leftJoinAndSelect('event.source', 'source')
.leftJoinAndSelect('event.activity', 'activity')
.leftJoinAndSelect('activity.subreddit', 'subreddit')
.leftJoinAndSelect('activity.author', 'author')
.leftJoinAndSelect('event.runResults', 'runResults')
.leftJoinAndSelect('activity.submission', 'activitySubmission')
.leftJoinAndSelect('activitySubmission.author', 'actSubAuthor');
query = filterResultsBuilder<CMEvent>(query, 'runResults', 'rr');
query.leftJoinAndSelect('runResults.run', 'run')
.leftJoinAndSelect('runResults.checkResults', 'checkResults');
query = filterResultsBuilder<CMEvent>(query, 'checkResults', 'c');
query.leftJoinAndSelect('checkResults.ruleResults', 'rrIterim')
.leftJoinAndSelect('rrIterim.result', 'ruleResult')
.leftJoinAndSelect('ruleResult.premise', 'rPremise')
.leftJoinAndSelect('rPremise.kind', 'ruleKind')
.leftJoinAndSelect('checkResults.ruleSetResults', 'ruleSetResultsIterim')
.leftJoinAndSelect('ruleSetResultsIterim.result', 'ruleSetResult')
.leftJoinAndSelect('ruleSetResult._ruleResults', 'rsRuleResultsIterim')
.leftJoinAndSelect('rsRuleResultsIterim.result', 'rsRuleResult')
.leftJoinAndSelect('rsRuleResult.premise', 'rsPremise')
.leftJoinAndSelect('rsPremise.kind', 'rsRuleKind')
.leftJoinAndSelect('checkResults.check', 'check');
query = filterResultsBuilder<CMEvent>(query, 'ruleResult', 'r');
query = filterResultsBuilder<CMEvent>(query, 'rsRuleResult', 'rsr');
query.leftJoinAndSelect('checkResults.actionResults', 'actionResults')
.leftJoinAndSelect('actionResults.premise', 'aPremise')
.leftJoinAndSelect('aPremise.kind', 'actionKind');
query = filterResultsBuilder<CMEvent>(query, 'actionResults', 'a');
query.orderBy('event._processedAt', 'DESC');
query.andWhereInIds(ids);
return query;
}
Example #9
Source File: util.ts From context-mod with MIT License | 6 votes |
getDistinctEventIdsWhereQuery = (dataSource: DataSource, opts: EventConditions): SelectQueryBuilder<CMEvent> => {
const query = getSimpleEventsWhereQuery(dataSource, opts);
// see comments about order by and take/skip in getSimpleEventsWhereQuery
//query.select('event.id');
return query;
}
Example #10
Source File: util.ts From context-mod with MIT License | 6 votes |
getSimpleEventsWhereQuery = (dataSource: DataSource, opts: EventConditions): SelectQueryBuilder<CMEvent> => {
const query = dataSource.getRepository(CMEvent)
.createQueryBuilder("event");
const {
managerIds,
related,
activity,
author,
} = opts;
query.andWhere('event.manager.id IN (:...managerIds)', {managerIds: managerIds});
if (activity !== undefined) {
query.leftJoinAndSelect('event.activity', 'activity');
if (related === undefined) {
query.andWhere('activity._id = :actId', {actId: activity.id});
} else {
if (related === 'all') {
query.leftJoinAndSelect('activity.author', 'author')
query.andWhere(new Brackets((qb) => {
qb.where(new Brackets(qbAct => orByRelatedActivities(activity, qbAct)))
.orWhere(new Brackets(qbAuthor => orByRelatedAuthor(activity, qbAuthor)));
}))
} else if (related === 'activity') {
query.andWhere(new Brackets((qb) => orByRelatedActivities(activity, qb)));
} else if (related === 'author') {
query.leftJoinAndSelect('activity.author', 'author')
query.andWhere(new Brackets((qb) => orByRelatedAuthor(activity, qb)));
}
}
} else if(author !== undefined) {
const authorVal = parseRedditEntity(author, 'user');
query.leftJoinAndSelect('event.activity', 'activity');
query.leftJoinAndSelect('activity.author', 'author')
.andWhere('author.name = :authorName', {authorName: authorVal.name});
}
// can't order by using this AND use "select event id only" in getDistinctEventIdsWhereQuery
// due to bug in how typeorm handles wrapping sub select for count when using take/skip
// https://github.com/typeorm/typeorm/issues/4742#issuecomment-858333515
// https://github.com/typeorm/typeorm/issues/747
// https://github.com/typeorm/typeorm/issues/3501
//query.orderBy('event._processedAt', 'DESC');
query.orderBy('event._processedAt', 'DESC');
//query.orderBy({'event._processedAt':'DESC'});
return query;
}
Example #11
Source File: singleton.ts From typeorm-extension with MIT License | 5 votes |
export function setDataSource(
dataSource: DataSource,
alias?: string,
) {
alias = alias || 'default';
instances[alias] = dataSource;
}
Example #12
Source File: singleton.ts From typeorm-extension with MIT License | 5 votes |
export async function useDataSource(alias?: string) : Promise<DataSource> {
alias = alias || 'default';
if (Object.prototype.hasOwnProperty.call(instances, alias)) {
if (!instances[alias].isInitialized) {
/* istanbul ignore next */
if (!Object.prototype.hasOwnProperty.call(initializePromises, alias)) {
initializePromises[alias] = instances[alias].initialize()
.catch((e) => {
delete initializePromises[alias];
throw e;
});
}
await initializePromises[alias];
}
return instances[alias];
}
/* istanbul ignore next */
if (!Object.prototype.hasOwnProperty.call(optionsPromises, alias)) {
optionsPromises[alias] = useDataSourceOptions(alias)
.catch((e) => {
delete optionsPromises[alias];
throw e;
});
}
const options = await optionsPromises[alias];
const dataSource = new DataSource(options);
/* istanbul ignore next */
if (!Object.prototype.hasOwnProperty.call(initializePromises, alias)) {
initializePromises[alias] = dataSource.initialize()
.catch((e) => {
delete initializePromises[alias];
throw e;
});
}
await initializePromises[alias];
instances[alias] = dataSource;
return dataSource;
}
Example #13
Source File: singleton.ts From typeorm-extension with MIT License | 5 votes |
instances : Record<string, DataSource> = {}
Example #14
Source File: singleton.ts From typeorm-extension with MIT License | 5 votes |
initializePromises : Record<string, Promise<DataSource>> = {}
Example #15
Source File: StorageProvider.ts From context-mod with MIT License | 5 votes |
database: DataSource;
Example #16
Source File: StorageProvider.ts From context-mod with MIT License | 5 votes |
constructor(data: { database: DataSource } & StorageProviderOptions) {
super(data);
this.database = data.database;
this.inviteRepo = this.database.getRepository(Invite);
this.webSettingRepo = this.database.getRepository(WebSetting);
this.clientSessionRepo = this.database.getRepository(ClientSession);
this.logger.debug('Using DATABASE');
}
Example #17
Source File: databaseUtils.ts From context-mod with MIT License | 5 votes |
createDatabaseConnection = async (rawConfig: DatabaseConfig, domainOptions: DomainSpecificDataSourceOptions, logger: Logger): Promise<DataSource> => {
let config = {...rawConfig};
const dbLogger = logger.child({labels: ['Database']}, mergeArr);
dbLogger.info(`Using '${rawConfig.type}' database type`);
if(rawConfig.type === 'sqljs') {
dbLogger.warn(`sqljs SHOULD NOT be used in a production environment. Consider switching to 'better-sqlite3' for better performance. Preferably 'mysql', 'mariadb', or 'postgres' for best performance and security.`);
}
if (['sqljs', 'better-sqlite3'].includes(rawConfig.type)) {
let dbOptions: Pick<SqljsConnectionOptions, 'autoSave' | 'location'> | Pick<BetterSqlite3ConnectionOptions, 'database'>
let dbPath: string | undefined;
const rawPath = rawConfig.type === 'sqljs' ? rawConfig.location : rawConfig.database;
if (typeof rawPath !== 'string' || (typeof rawPath === 'string' && rawPath.trim().toLocaleLowerCase() === ':memory:')) {
dbLogger.warn('Will use IN-MEMORY database. All data will be lost on application restart.');
} else {
try {
dbLogger.debug('Testing that database path is writeable...');
fileOrDirectoryIsWriteable(rawPath);
dbPath = rawPath;
dbLogger.verbose(`Using database at path: ${rawPath}`);
} catch (e: any) {
dbLogger.error(new ErrorWithCause(`Falling back to IN-MEMORY database due to error while trying to access database. All data will be lost on application restart`, {cause: e}));
if(castToBool(process.env.IS_DOCKER) === true) {
dbLogger.info(`Make sure you have specified user in docker run command! See https://github.com/FoxxMD/context-mod/blob/master/docs/gettingStartedOperator.md#docker-recommended`);
}
}
}
if (rawConfig.type === 'sqljs') {
dbOptions = {
autoSave: dbPath !== undefined,
location: dbPath
};
} else {
dbOptions = {
database: dbPath ?? ':memory:'
}
}
config = {...config, ...dbOptions} as SqljsConnectionOptions | BetterSqlite3ConnectionOptions;
}
const {
logging = ['error', 'warn', 'schema'],
...rest
} = config;
let logTypes: any = logging;
if(logTypes === true) {
logTypes = ['ALL (logging=true)'];
} else if (logTypes === false) {
logTypes = ['NONE (logging=false)'];
}
dbLogger.debug(`Will log the follow types from typeorm: ${logTypes.join(', ')}`);
const source = new DataSource({
...rest,
synchronize: false,
...domainOptions,
migrationsRun: false,
logging: ['error', 'warn', 'migration', 'schema', 'log'],
logger: new WinstonAdaptor(dbLogger, logging, false, ormLoggingAdaptorLevelMappings(dbLogger)),
namingStrategy: new CMNamingStrategy(),
});
await source.initialize();
return source;
}
Example #18
Source File: MigrationService.ts From context-mod with MIT License | 5 votes |
database: DataSource;
Example #19
Source File: FakeSelectQueryBuilder.ts From typeorm-extension with MIT License | 5 votes |
constructor() {
super({
options: {}
} as DataSource);
}
Example #20
Source File: data-source.ts From typeorm-extension with MIT License | 5 votes |
dataSource = new DataSource(options)
Example #21
Source File: index.ts From context-mod with MIT License | 5 votes |
database: DataSource
Example #22
Source File: module.ts From typeorm-extension with MIT License | 4 votes |
export async function findDataSource(
context?: DataSourceFindOptions,
) : Promise<DataSource | undefined> {
const fileNames : string[] = [
'data-source',
];
context = context || {};
if (context.fileName) {
fileNames.unshift(context.fileName);
}
const basePaths = [
process.cwd(),
];
if (
context.directory &&
context.directory !== process.cwd()
) {
context.directory = path.isAbsolute(context.directory) ?
context.directory :
path.join(process.cwd(), context.directory);
basePaths.unshift(context.directory);
}
const directories = [
path.join('src', 'db'),
path.join('src', 'database'),
path.join('src'),
];
let paths : string[] = [];
for (let i = 0; i < basePaths.length; i++) {
paths.push(basePaths[i]);
if (basePaths[i] === process.cwd()) {
for (let j = 0; j < directories.length; j++) {
paths.push(path.join(basePaths[i], directories[j]));
}
}
}
if (!isTsNodeRuntimeEnvironment()) {
let tsConfigFound = false;
for (let i = 0; i < basePaths.length; i++) {
const { compilerOptions } = await readTsConfig(basePaths[i]);
if (compilerOptions) {
paths = paths.map((item) => changeTSToJSPath(item, { dist: compilerOptions.outDir }));
tsConfigFound = true;
break;
}
}
if (!tsConfigFound) {
paths = paths.map((item) => changeTSToJSPath(item));
}
}
for (let i = 0; i < fileNames.length; i++) {
const info = await locateFile(`${fileNames[i]}.{js,ts}`, {
path: paths,
});
if (info) {
const fileExports = await loadScriptFile(info);
if (InstanceChecker.isDataSource(fileExports)) {
return fileExports;
}
if (typeof fileExports === 'object') {
const keys = Object.keys(fileExports);
for (let j = 0; j < keys.length; j++) {
const value = (fileExports as Record<string, any>)[keys[i]];
if (InstanceChecker.isDataSource(value)) {
return value;
}
}
}
}
}
return undefined;
}