database.ts 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /**
  2. * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Table } from './table';
  7. /** A collection of tables */
  8. type Database<Schema extends Database.Schema> = {
  9. readonly _name: string,
  10. readonly _tableNames: ReadonlyArray<string>,
  11. readonly _schema: Schema
  12. } & Database.Tables<Schema>
  13. namespace Database {
  14. export type Tables<S extends Schema> = { [T in keyof S]: Table<S[T]> }
  15. export type Schema = { [table: string]: Table.Schema }
  16. export function ofTables<S extends Schema>(name: string, schema: Schema, tables: Tables<S>) {
  17. const keys = Object.keys(tables);
  18. const ret = Object.create(null);
  19. const tableNames: string[] = [];
  20. ret._name = name;
  21. ret._tableNames = tableNames;
  22. ret._schema = schema;
  23. for (const k of keys) {
  24. if (!Table.is(tables[k])) continue;
  25. ret[k] = tables[k];
  26. tableNames[tableNames.length] = k;
  27. }
  28. return ret;
  29. }
  30. export function getTablesAsRows<S extends Schema>(database: Database<S>) {
  31. const ret: { [k: string]: Table.Row<any>[] } = {};
  32. for (const k of database._tableNames) {
  33. ret[k] = Table.getRows(database[k]);
  34. }
  35. return ret;
  36. }
  37. }
  38. export { Database };