ihp-datasync-typescript (empty) → 1.5.0
raw patch · 7 files changed
+1048/−0 lines, 7 filesdep +hspecdep +ihpdep +ihp-datasync-typescript
Dependencies added: hspec, ihp, ihp-datasync-typescript, ihp-postgres-parser, megaparsec, neat-interpolation, text, with-utf8
Files
- IHP/DataSync/TypeScript/Compiler.hs +451/−0
- LICENSE +21/−0
- README.md +37/−0
- Test/Spec.hs +442/−0
- changelog.md +9/−0
- exe/GenerateDataSyncTypes.hs +27/−0
- ihp-datasync-typescript.cabal +61/−0
+ IHP/DataSync/TypeScript/Compiler.hs view
@@ -0,0 +1,451 @@+module IHP.DataSync.TypeScript.Compiler where++import IHP.Prelude+import IHP.Postgres.Types++generateTypeScriptTypeDefinitions :: [Statement] -> Text+generateTypeScriptTypeDefinitions schema = [trimming|+declare module 'ihp-datasync' {+ ${tableNameTypeDef}+ ${tableNameToRecordType}+ ${enumTypes}+ ${recordInterfaces}+ ${newRecordInterfaces}+ ${newRecordType'}++ type UUID = string;++ class ConditionBuildable<table extends TableName, T extends ConditionBuildable<table, T>> {+ conditionBuildableType: table;++ where<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ where(conditionBuilder: ConditionBuilder<table>): T;+ where(filterRecord: Partial<IHPRecord<table>>): T;+ filterWhere<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereNot<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereLessThan<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereLessThanOrEqual<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereGreaterThan<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereGreaterThanOrEqual<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;++ or (...conditionBuilder: ConditionBuilder<table>[]): T;+ and(...conditionBuilder: ConditionBuilder<table>[]): T;++ whereIn<column extends keyof IHPRecord<table>>(column: column, value: Array<IHPRecord<table>[column]>): T;+ }++ class ConditionBuilder<table extends TableName> extends ConditionBuildable<table, ConditionBuilder<table>> {}++ function or <table extends TableName>( conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;+ function or <table extends TableName>(...conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;+ function and<table extends TableName>( conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;+ function and<table extends TableName>(...conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;++ class QueryBuilder<table extends TableName, result extends {}> extends ConditionBuildable<table, QueryBuilder<table, result>> {+ query: Query;++ select<column extends keyof IHPRecord<table>>(columns: column[]): QueryBuilder<table, (result extends IHPRecord<table> ? {} : result) & Pick<IHPRecord<table>, column>>;+ select<column extends keyof IHPRecord<table>>(...columns: column[]): QueryBuilder<table, (result extends IHPRecord<table> ? {} : result) & Pick<IHPRecord<table>, column>>;++ whereTextSearchStartsWith<column extends keyof IHPRecord<table>, value extends IHPRecord<table>[column] & string>(column: column, value: value): QueryBuilder<table, result>;++ orderBy(column: keyof IHPRecord<table>): QueryBuilder<table, result>;+ orderByAsc(column: keyof IHPRecord<table>): QueryBuilder<table, result>;+ orderByDesc(column: keyof IHPRecord<table>): QueryBuilder<table, result>;+ limit(limit: number): QueryBuilder<table, result>;+ offset(limit: number): QueryBuilder<table, result>;++ fetch(): Promise<Array<result>>;+ fetchOne(): Promise<result>;+ subscribe(subscribe: (value: Array<result>) => void): (() => void);+ }+ + ${conditionBuilderConstructors}++ interface Query<table extends TableName, result> {+ table: table;+ }+ + /**+ * Returns a new database query builder.+ * + * @example+ * const tasks = await query('tasks')+ * .orderBy('createdAt')+ * .limit(10)+ * .fetch();+ * + * @param {string} table The name of one of your project's table.+ */+ function query<table extends TableName>(table: table): QueryBuilder<table, IHPRecord<table>>;+ function query<table extends TableName, column extends keyof IHPRecord<table>>(table: table, columns: column[]): QueryBuilder<table, Pick<IHPRecord<table>, column>>;++ class DataSubscription<table extends TableName, record> {+ isClosed: boolean;+ isConnected: boolean;++ constructor(query: Query<table, record>);+ createOnServer(): Promise<void>;+ close(): Promise<void>;+ closeIfNotUsed(): Promise<void>;+ getRecords(): Array<object>;+ subscribe(subscribe: (value: Array<record>) => void): (() => void);+ }++ ${initThinBackendTypeDef'}++ /**+ * Creates a row inside a database table. Returns a promise of the newly created object.+ * + * @example+ * const task = await createRecord('tasks', {+ * title: 'Hello World',+ * userId: getCurrentUserId()+ * })+ * @param {string} tableName The name of one of your project's table.+ * @param {object} record An object representing the row to be inserted. Columns with a database-side default value don't need to be specified.+ * @see {@link createRecords} You can use `createRecords` to batch insert multiple records in an efficient way+ */+ function createRecord<table extends TableName>(tableName: table, record: NewRecord<IHPRecord<table>>): Promise<IHPRecord<table>>;++ /**+ * Updates a row inside a database table. Returns a promise of the updated row.+ * + * @example+ * updateRecord('tasks', task.id, {+ * isCompleted: true+ * })+ * @param {string} tableName The name of one of your project's table+ * @param {UUID} id The id of the row to be updated+ * @param {object} patch An patch object representing the changed values.+ */+ function updateRecord<table extends TableName>(tableName: table, id: UUID, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<IHPRecord<table>>;++ /**+ * Updates multiple rows inside a database table. Returns a promise of the updated rows.+ * + * @example+ * const taskIds = tasks.map(taks => task.id);+ * updateRecords('tasks', taskIds, {+ * isCompleted: true+ * })+ * @param {string} tableName The name of one of your project's table+ * @param {Array<UUID>} ids The ids of the rows to be updated+ * @param {object} patch An patch object representing the changed values.+ */+ function updateRecords<table extends TableName>(tableName: table, ids: Array<UUID>, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;++ /**+ * Deletes a row inside a database table.+ * + * @example+ * deleteRecord('tasks', task.id)+ * @param {string} tableName The name of one of your project's table+ * @param {UUID} id The id of the row to be deleted+ */+ function deleteRecord<table extends TableName>(tableName: table, id: UUID): Promise<void>;++ /**+ * Deletes multiple rows inside a database table.+ * + * @example+ * const taskIds = tasks.map(task => task.id)+ * deleteRecords('tasks', taskIds)+ * @param {string} tableName The name of one of your project's table+ * @param {Array<UUID>} ids The ids of the rows to be deleted+ */+ function deleteRecords<table extends TableName>(tableName: table, ids: Array<UUID>): Promise<void>;++ /**+ * Creates multiple rows inside a database table in a single INSERT query. Returns a promise of the newly created objects.+ * + * @example+ * const tasksToCreate = [];+ * + * // Make 10 task objects, but don't insert them to the DB yet+ * for (let i = 0; i < 10; i++) {+ * tasksToCreate.push({+ * title: `Task $${i}`,+ * userId: getCurrentUserId()+ * });+ * }+ * + * // Insert the 10 tasks+ * const tasks = await createRecords('tasks', tasksToCreate)+ * @param {string} tableName The name of one of your project's table.+ * @param {object} records An array representing the rows to be inserted.+ */+ function createRecords<table extends TableName>(tableName: table, records: Array<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;++ function getCurrentUserId(): string;+ function getCurrentUser(): Promise<User | null>;++ interface LogoutOptions {+ redirect?: string;+ }++ function logout(options?: LogoutOptions): Promise<void>;+ + /**+ * Useful to implement a login button. Redirects the user to the login page.+ *+ * The returned promise never resolves, as the browser is redirected to a different page.+ * + * @example+ * import { loginWithRedirect } from 'ihp-datasync';+ * function LoginButton() {+ * const isLoading = useState(false);+ *+ * const doLogin = async () => {+ * setLoading(true);+ * await loginWithRedirect();+ * setLoading(false);+ * }+ *+ * return <button onClick={doLogin} disabled={isLoading}>Login</button>+ * }+ */ + function loginWithRedirect(): Promise<void>;+ function ensureIsUser(): Promise<void>;+ function initAuth(): Promise<void>;++ class Transaction {+ public transactionId: UUID | null;++ start(): Promise<void>;+ commit(): Promise<void>;+ rollback(): Promise<void>;+ + query<table extends TableName>(table: table): QueryBuilder<table, IHPRecord<table>>;+ query<table extends TableName, column extends keyof IHPRecord<table>>(table: table, columns: column[]): QueryBuilder<table, Pick<IHPRecord<table>, column>>;+ + createRecord<table extends TableName>(tableName: table, record: NewRecord<IHPRecord<table>>): Promise<IHPRecord<table>>;+ createRecords<table extends TableName>(tableName: table, records: Array<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;+ updateRecord<table extends TableName>(tableName: table, id: UUID, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<IHPRecord<table>>;+ updateRecords<table extends TableName>(tableName: table, ids: Array<UUID>, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;+ deleteRecord<table extends TableName>(tableName: table, id: UUID): Promise<void>;+ deleteRecords<table extends TableName>(tableName: table, ids: Array<UUID>): Promise<void>;+ }++ function withTransaction<returnValue>(callback: ((transaction: Transaction) => Promise<returnValue>) ): Promise<returnValue>;++ const enum NewRecordBehaviour {+ APPEND_NEW_RECORD = 0,+ PREPEND_NEW_RECORD = 1+ }+ interface DataSubscriptionOptions {+ /** When you add a new record, you might want the new record to be always displayed at the start of the list for UX reasons, ignoring any sort behaviour specified in the order by of the database query. */+ newRecordBehaviour: NewRecordBehaviour; + }+}++declare module 'ihp-datasync/react' {+ import { TableName, QueryBuilder, User, DataSubscriptionOptions } from 'ihp-datasync';++ /**+ * React hook for querying the database and streaming results in real-time+ * + * @example+ * function TasksList() {+ * const tasks = useQuery(query('tasks').orderBy('createdAt'))+ * + * return <div>+ * {tasks.map(task => <div>{task.title}</div>)}+ * </div>+ * }+ * + * @param {QueryBuilder<table, result>} queryBuilder A database query+ */+ function useQuery<table extends TableName, result>(queryBuilder: QueryBuilder<table, result>, options?: DataSubscriptionOptions): Array<result> | null;++ function useCount<table extends TableName>(queryBuilder: QueryBuilder<table, any>): number | null;++ /**+ * A version of `useQuery` when you only want to fetch a single record.+ * + * Automatically adds a `.limit(1)` to the query and returns the single result instead of a list.+ * + * @example+ * const message = useQuerySingleresult(query('messages').filterWhere('id', '1f290b39-c6d1-4dff-8404-0581f470253c'));+ */+ function useQuerySingleResult<table extends TableName, result>(queryBuilder: QueryBuilder<table, result>): result | null;++ function useCurrentUser(): User | null;+ + /**+ * Returns true if there's a user logged in. Returns false if there's no logged in user. Returns null if loading.+ * + * @example+ * const isLoggedIn = useIsLoggedIn();+ */+ function useIsLoggedIn(): boolean | null;++ /**+ * Returns true if the frontend is online and connected to the server. Returns false if the internet connection is offline and not connected to the server.+ * + * @example+ * const isConnected = useIsConnected();+ */+ function useIsConnected(): boolean;++ interface ThinBackendProps {+ requireLogin?: boolean;+ children: JSX.Element[] | JSX.Element;+ }+ function ThinBackend(props: ThinBackendProps): JSX.Element;+}+|]+ where+ tableNameTypeDef :: Text+ tableNameTypeDef = "type TableName = " <> (tableNames |> map tshow |> intercalate " | " ) <> ";"++ tableNames :: [Text]+ tableNames = createTableStatements |> map (get #name)++ createTableStatements :: [CreateTable]+ createTableStatements = + schema |> mapMaybe \case+ StatementCreateTable { unsafeGetCreateTable = table } -> Just table+ otherwise -> Nothing++ recordInterfaces :: Text+ recordInterfaces = createTableStatements+ |> map recordInterface+ |> intercalate "\n"+ + newRecordInterfaces :: Text+ newRecordInterfaces = createTableStatements+ |> map newRecordInterface+ |> intercalate "\n"+ + enumTypes :: Text+ enumTypes = + schema+ |> mapMaybe \case+ CreateEnumType { name, values } -> Just (generateEnumType name values)+ otherwise -> Nothing+ |> intercalate "\n"++ tableNameToRecordType :: Text+ tableNameToRecordType = [trimming|+ type IHPRecord<table> = ${implementation};+ |]+ where+ -- table extends "users" ? UserRecord : (table extends "tasks" ? TaskRecord : never)+ implementation = gen createTableStatements++ gen [] = "never"+ gen (table:rest) = "table extends " <> tshow (get #name table) <> " ? " <> tableNameToModelName (get #name table) <> " : (" <> gen rest <> ")"++ newRecordType' :: Text+ newRecordType' = newRecordType createTableStatements++ initThinBackendTypeDef' :: Text+ initThinBackendTypeDef' = initThinBackendTypeDef++ conditionBuilderConstructors :: Text+ conditionBuilderConstructors = tableNames+ |> map forTable+ |> intercalate "\n"+ where+ forTable tableName = [trimming|function where(conditionBuilder: ConditionBuilder<'${tableName}'>): ConditionBuilder<'${tableName}'>;+function where(filterRecord: Partial<${record}>) : ConditionBuilder<'${tableName}'>;+function where <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function filterWhere <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function eq <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function notEq <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function lessThan <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function lessThanOrEqual <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function greaterThan <column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;+function greaterThanOrEqual<column extends keyof ${record}>(column: column, value: ${record}[column]): ConditionBuilder<'${tableName}'>;|]+ where+ record = tableNameToModelName tableName++recordInterface :: CreateTable -> Text+recordInterface CreateTable { name, columns } = "interface " <> tableNameToModelName name <> " {\n" <> fields <> "\n}"+ where+ fields = columns+ |> map columnToField+ |> intercalate "\n"+ columnToField Column { name, columnType, notNull } = " " <> columnNameToFieldName name <> ": " <> columnTypeToTypeScript columnType notNull <> ";"++-- | Generates a record interface where fields with default values are optional+newRecordInterface :: CreateTable -> Text+newRecordInterface CreateTable { name, columns } = [trimming|+ /**+ * ${description}+ */+ interface New${modelName} {+ ${fields}+ }+ |]+ where+ fields = columns+ |> map columnToField+ |> intercalate "\n"+ columnToField Column { name, columnType, notNull, defaultValue } = columnNameToFieldName name <> (if isJust defaultValue then "?" else "") <> ": " <> columnTypeToTypeScript columnType notNull <> ";"++ modelName :: Text+ modelName = tableNameToModelName name++ description :: Text+ description = "A " <> modelName <> " object not yet inserted into the `" <> name <> "` table"++columnTypeToTypeScript :: PostgresType -> Bool -> Text+columnTypeToTypeScript sqlType notNull =+ if notNull+ then columnTypeToTypeScript' sqlType+ else columnTypeToTypeScript' sqlType <> " | null"++columnTypeToTypeScript' :: PostgresType -> Text+columnTypeToTypeScript' PText = "string"+columnTypeToTypeScript' PInt = "number"+columnTypeToTypeScript' PSmallInt = "number"+columnTypeToTypeScript' PDouble = "number"+columnTypeToTypeScript' PBoolean = "boolean"+columnTypeToTypeScript' PUUID = "UUID"+columnTypeToTypeScript' (PCustomType customType) = tableNameToModelName customType+columnTypeToTypeScript' (PArray inner) = "Array<" <> columnTypeToTypeScript' inner <> ">"+columnTypeToTypeScript' otherwise = "string"++newRecordType :: [CreateTable] -> Text+newRecordType createTableStatements = [trimming|+ type NewRecord<Type> = ${implementation};+|]+ where+ -- table extends "users" ? UserRecord : (table extends "tasks" ? TaskRecord : never)+ implementation = gen createTableStatements++ gen [] = "never"+ gen (table:rest) = "Type extends " <> tableNameToModelName (get #name table) <> " ? New" <> tableNameToModelName (get #name table) <> " : (" <> gen rest <> ")"+++initThinBackendTypeDef :: Text+initThinBackendTypeDef = [trimming|+ function initThinBackend(options: { host: string | undefined; }): void;+|]++++packageJsonContent :: Text+packageJsonContent = [trimming|+{+ "name": "@types/ihp-datasync",+ "version": "1.0.0",+ "description": "",+ "main": "index.js",+ "scripts": {+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "author": "",+ "license": "ISC",+ "types": "main.d.ts"+}+|]++generateEnumType :: Text -> [Text] -> Text+generateEnumType _ [] = ""+generateEnumType name values = "type " <> tableNameToModelName name <> " = " <> (intercalate " | " (map compileValue values)) <> ";"+ where+ compileValue :: Text -> Text+ compileValue value = "'" <> value <> "'"
+ LICENSE view
@@ -0,0 +1,21 @@+The MIT License (MIT)++Copyright (c) 2020 digitally induced GmbH++Permission is hereby granted, free of charge, to any person obtaining a copy+of this software and associated documentation files (the "Software"), to deal+in the Software without restriction, including without limitation the rights+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell+copies of the Software, and to permit persons to whom the Software is+furnished to do so, subject to the following conditions:++The above copyright notice and this permission notice shall be included in all+copies or substantial portions of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE+SOFTWARE.
+ README.md view
@@ -0,0 +1,37 @@+# ihp-datasync-typescript++1. Add `ihp-datasync-typescript` to `flake.nix`+2. Run `generate-datasync-types Application/Schema.sql Frontend/types/ihp-datasync/index.d.ts`++Requires a `typeRoots` in `tsconfig.json` like this:++```json+{+ "compilerOptions": {+ "target": "es6",+ "lib": [+ "dom",+ "dom.iterable",+ "esnext"+ ],+ "allowJs": true,+ "skipLibCheck": true,+ "esModuleInterop": true,+ "allowSyntheticDefaultImports": true,+ "strict": true,+ "forceConsistentCasingInFileNames": true,+ "noFallthroughCasesInSwitch": true,+ "module": "esnext",+ "moduleResolution": "node",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "noEmit": true,+ "jsx": "react-jsx",+ "typeRoots": ["./node_modules/@types", "./Frontend/types"],+ "declaration": true,+ },+ "include": [+ "src"+ ]+}+```
+ Test/Spec.hs view
@@ -0,0 +1,442 @@+module Main where++import Test.Hspec+import IHP.Prelude+import IHP.DataSync.TypeScript.Compiler++import qualified IHP.Postgres.Parser as Parser+import IHP.Postgres.Types+import qualified Text.Megaparsec as Megaparsec++main :: IO ()+main = hspec tests++tests = do+ describe "Test.Web.View.TypeDefinitions.TypeScript" do+ describe "generateTypeScriptTypeDefinitions" do+ it "should generate a valid typescript definition file" do+ let schema = parseSqlStatements $ cs [plain|+ CREATE TABLE users (+ id UUID DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,+ email TEXT NOT NULL,+ password_hash TEXT NOT NULL,+ locked_at TIMESTAMP WITH TIME ZONE DEFAULT NULL,+ failed_login_attempts INT DEFAULT 0 NOT NULL,+ access_token TEXT DEFAULT NULL+ );+ CREATE TYPE colors AS ENUM ('red', 'blue');+ CREATE TABLE tasks (+ id UUID DEFAULT uuid_generate_v4() PRIMARY KEY NOT NULL,+ title TEXT NOT NULL,+ created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,+ user_id UUID NOT NULL,+ color colors NOT NULL,+ color_arr colors[] NOT NULL+ );+ CREATE INDEX tasks_user_id_index ON tasks (user_id);+ ALTER TABLE tasks ADD CONSTRAINT tasks_ref_user_id FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE NO ACTION;+ CREATE POLICY "Users can manage their tasks" ON tasks USING (user_id = ihp_user_id()) WITH CHECK (user_id = ihp_user_id());+ ALTER TABLE tasks ENABLE ROW LEVEL SECURITY;+ |]+ let expected = [trimming|+ declare module 'ihp-datasync' {+ type TableName = "users" | "tasks";+ type IHPRecord<table> = table extends "users" ? User : (table extends "tasks" ? Task : (never));+ type Color = 'red' | 'blue';+ interface User {+ id: UUID;+ email: string;+ passwordHash: string;+ lockedAt: string | null;+ failedLoginAttempts: number;+ accessToken: string | null;+ }+ interface Task {+ id: UUID;+ title: string;+ createdAt: string;+ userId: UUID;+ color: Color;+ colorArr: Array<Color>;+ }+ /**+ * A User object not yet inserted into the `users` table+ */+ interface NewUser {+ id?: UUID;+ email: string;+ passwordHash: string;+ lockedAt?: string | null;+ failedLoginAttempts?: number;+ accessToken?: string | null;+ }+ /**+ * A Task object not yet inserted into the `tasks` table+ */+ interface NewTask {+ id?: UUID;+ title: string;+ createdAt?: string;+ userId: UUID;+ color: Color;+ colorArr: Array<Color>;+ }+ type NewRecord<Type> = Type extends User ? NewUser : (Type extends Task ? NewTask : (never));++ type UUID = string;++ class ConditionBuildable<table extends TableName, T extends ConditionBuildable<table, T>> {+ conditionBuildableType: table;++ where<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ where(conditionBuilder: ConditionBuilder<table>): T;+ where(filterRecord: Partial<IHPRecord<table>>): T;+ filterWhere<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereNot<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereLessThan<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereLessThanOrEqual<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereGreaterThan<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;+ whereGreaterThanOrEqual<column extends keyof IHPRecord<table>>(column: column, value: IHPRecord<table>[column]): T;++ or (...conditionBuilder: ConditionBuilder<table>[]): T;+ and(...conditionBuilder: ConditionBuilder<table>[]): T;++ whereIn<column extends keyof IHPRecord<table>>(column: column, value: Array<IHPRecord<table>[column]>): T;+ }++ class ConditionBuilder<table extends TableName> extends ConditionBuildable<table, ConditionBuilder<table>> {}++ function or <table extends TableName>( conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;+ function or <table extends TableName>(...conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;+ function and<table extends TableName>( conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;+ function and<table extends TableName>(...conditions: ConditionBuilder<table>[]): ConditionBuilder<table>;++ class QueryBuilder<table extends TableName, result extends {}> extends ConditionBuildable<table, QueryBuilder<table, result>> {+ query: Query;++ select<column extends keyof IHPRecord<table>>(columns: column[]): QueryBuilder<table, (result extends IHPRecord<table> ? {} : result) & Pick<IHPRecord<table>, column>>;+ select<column extends keyof IHPRecord<table>>(...columns: column[]): QueryBuilder<table, (result extends IHPRecord<table> ? {} : result) & Pick<IHPRecord<table>, column>>;++ whereTextSearchStartsWith<column extends keyof IHPRecord<table>, value extends IHPRecord<table>[column] & string>(column: column, value: value): QueryBuilder<table, result>;++ orderBy(column: keyof IHPRecord<table>): QueryBuilder<table, result>;+ orderByAsc(column: keyof IHPRecord<table>): QueryBuilder<table, result>;+ orderByDesc(column: keyof IHPRecord<table>): QueryBuilder<table, result>;+ limit(limit: number): QueryBuilder<table, result>;+ offset(limit: number): QueryBuilder<table, result>;++ fetch(): Promise<Array<result>>;+ fetchOne(): Promise<result>;+ subscribe(subscribe: (value: Array<result>) => void): (() => void);+ }+ + function where(conditionBuilder: ConditionBuilder<'users'>): ConditionBuilder<'users'>;+ function where(filterRecord: Partial<User>) : ConditionBuilder<'users'>;+ function where <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function filterWhere <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function eq <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function notEq <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function lessThan <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function lessThanOrEqual <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function greaterThan <column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function greaterThanOrEqual<column extends keyof User>(column: column, value: User[column]): ConditionBuilder<'users'>;+ function where(conditionBuilder: ConditionBuilder<'tasks'>): ConditionBuilder<'tasks'>;+ function where(filterRecord: Partial<Task>) : ConditionBuilder<'tasks'>;+ function where <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function filterWhere <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function eq <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function notEq <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function lessThan <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function lessThanOrEqual <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function greaterThan <column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;+ function greaterThanOrEqual<column extends keyof Task>(column: column, value: Task[column]): ConditionBuilder<'tasks'>;++ interface Query<table extends TableName, result> {+ table: table;+ }+ + /**+ * Returns a new database query builder.+ * + * @example+ * const tasks = await query('tasks')+ * .orderBy('createdAt')+ * .limit(10)+ * .fetch();+ * + * @param {string} table The name of one of your project's table.+ */+ function query<table extends TableName>(table: table): QueryBuilder<table, IHPRecord<table>>;+ function query<table extends TableName, column extends keyof IHPRecord<table>>(table: table, columns: column[]): QueryBuilder<table, Pick<IHPRecord<table>, column>>;++ class DataSubscription<table extends TableName, record> {+ isClosed: boolean;+ isConnected: boolean;++ constructor(query: Query<table, record>);+ createOnServer(): Promise<void>;+ close(): Promise<void>;+ closeIfNotUsed(): Promise<void>;+ getRecords(): Array<object>;+ subscribe(subscribe: (value: Array<record>) => void): (() => void);+ }++ function initThinBackend(options: { host: string | undefined; }): void;++ /**+ * Creates a row inside a database table. Returns a promise of the newly created object.+ * + * @example+ * const task = await createRecord('tasks', {+ * title: 'Hello World',+ * userId: getCurrentUserId()+ * })+ * @param {string} tableName The name of one of your project's table.+ * @param {object} record An object representing the row to be inserted. Columns with a database-side default value don't need to be specified.+ * @see {@link createRecords} You can use `createRecords` to batch insert multiple records in an efficient way+ */+ function createRecord<table extends TableName>(tableName: table, record: NewRecord<IHPRecord<table>>): Promise<IHPRecord<table>>;++ /**+ * Updates a row inside a database table. Returns a promise of the updated row.+ * + * @example+ * updateRecord('tasks', task.id, {+ * isCompleted: true+ * })+ * @param {string} tableName The name of one of your project's table+ * @param {UUID} id The id of the row to be updated+ * @param {object} patch An patch object representing the changed values.+ */+ function updateRecord<table extends TableName>(tableName: table, id: UUID, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<IHPRecord<table>>;+ + /**+ * Updates multiple rows inside a database table. Returns a promise of the updated rows.+ * + * @example+ * const taskIds = tasks.map(taks => task.id);+ * updateRecords('tasks', taskIds, {+ * isCompleted: true+ * })+ * @param {string} tableName The name of one of your project's table+ * @param {Array<UUID>} ids The ids of the rows to be updated+ * @param {object} patch An patch object representing the changed values.+ */+ function updateRecords<table extends TableName>(tableName: table, ids: Array<UUID>, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;++ /**+ * Deletes a row inside a database table.+ * + * @example+ * deleteRecord('tasks', task.id)+ * @param {string} tableName The name of one of your project's table+ * @param {UUID} id The id of the row to be deleted+ */+ function deleteRecord<table extends TableName>(tableName: table, id: UUID): Promise<void>;++ /**+ * Deletes multiple rows inside a database table.+ * + * @example+ * const taskIds = tasks.map(task => task.id)+ * deleteRecords('tasks', taskIds)+ * @param {string} tableName The name of one of your project's table+ * @param {Array<UUID>} ids The ids of the rows to be deleted+ */+ function deleteRecords<table extends TableName>(tableName: table, ids: Array<UUID>): Promise<void>;++ /**+ * Creates multiple rows inside a database table in a single INSERT query. Returns a promise of the newly created objects.+ * + * @example+ * const tasksToCreate = [];+ * + * // Make 10 task objects, but don't insert them to the DB yet+ * for (let i = 0; i < 10; i++) {+ * tasksToCreate.push({+ * title: `Task $${i}`,+ * userId: getCurrentUserId()+ * });+ * }+ * + * // Insert the 10 tasks+ * const tasks = await createRecords('tasks', tasksToCreate)+ * @param {string} tableName The name of one of your project's table.+ * @param {object} records An array representing the rows to be inserted.+ */+ function createRecords<table extends TableName>(tableName: table, records: Array<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;++ function getCurrentUserId(): string;+ function getCurrentUser(): Promise<User | null>;++ interface LogoutOptions {+ redirect?: string;+ }++ function logout(options?: LogoutOptions): Promise<void>;+ + /**+ * Useful to implement a login button. Redirects the user to the login page.+ *+ * The returned promise never resolves, as the browser is redirected to a different page.+ * + * @example+ * import { loginWithRedirect } from 'ihp-datasync';+ * function LoginButton() {+ * const isLoading = useState(false);+ *+ * const doLogin = async () => {+ * setLoading(true);+ * await loginWithRedirect();+ * setLoading(false);+ * }+ *+ * return <button onClick={doLogin} disabled={isLoading}>Login</button>+ * }+ */ + function loginWithRedirect(): Promise<void>;+ function ensureIsUser(): Promise<void>;+ function initAuth(): Promise<void>;++ class Transaction {+ public transactionId: UUID | null;++ start(): Promise<void>;+ commit(): Promise<void>;+ rollback(): Promise<void>;+ + query<table extends TableName>(table: table): QueryBuilder<table, IHPRecord<table>>;+ query<table extends TableName, column extends keyof IHPRecord<table>>(table: table, columns: column[]): QueryBuilder<table, Pick<IHPRecord<table>, column>>;+ + createRecord<table extends TableName>(tableName: table, record: NewRecord<IHPRecord<table>>): Promise<IHPRecord<table>>;+ createRecords<table extends TableName>(tableName: table, records: Array<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;+ updateRecord<table extends TableName>(tableName: table, id: UUID, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<IHPRecord<table>>;+ updateRecords<table extends TableName>(tableName: table, ids: Array<UUID>, patch: Partial<NewRecord<IHPRecord<table>>>): Promise<Array<IHPRecord<table>>>;+ deleteRecord<table extends TableName>(tableName: table, id: UUID): Promise<void>;+ deleteRecords<table extends TableName>(tableName: table, ids: Array<UUID>): Promise<void>;+ }++ function withTransaction<returnValue>(callback: ((transaction: Transaction) => Promise<returnValue>) ): Promise<returnValue>;++ const enum NewRecordBehaviour {+ APPEND_NEW_RECORD = 0,+ PREPEND_NEW_RECORD = 1+ }+ interface DataSubscriptionOptions {+ /** When you add a new record, you might want the new record to be always displayed at the start of the list for UX reasons, ignoring any sort behaviour specified in the order by of the database query. */+ newRecordBehaviour: NewRecordBehaviour; + }+ }++ declare module 'ihp-datasync/react' {+ import { TableName, QueryBuilder, User, DataSubscriptionOptions } from 'ihp-datasync';++ /**+ * React hook for querying the database and streaming results in real-time+ * + * @example+ * function TasksList() {+ * const tasks = useQuery(query('tasks').orderBy('createdAt'))+ * + * return <div>+ * {tasks.map(task => <div>{task.title}</div>)}+ * </div>+ * }+ * + * @param {QueryBuilder<table, result>} queryBuilder A database query+ */+ function useQuery<table extends TableName, result>(queryBuilder: QueryBuilder<table, result>, options?: DataSubscriptionOptions): Array<result> | null;++ function useCount<table extends TableName>(queryBuilder: QueryBuilder<table, any>): number | null;++ /**+ * A version of `useQuery` when you only want to fetch a single record.+ * + * Automatically adds a `.limit(1)` to the query and returns the single result instead of a list.+ * + * @example+ * const message = useQuerySingleresult(query('messages').filterWhere('id', '1f290b39-c6d1-4dff-8404-0581f470253c'));+ */+ function useQuerySingleResult<table extends TableName, result>(queryBuilder: QueryBuilder<table, result>): result | null;++ function useCurrentUser(): User | null;+ + /**+ * Returns true if there's a user logged in. Returns false if there's no logged in user. Returns null if loading.+ * + * @example+ * const isLoggedIn = useIsLoggedIn();+ */+ function useIsLoggedIn(): boolean | null;++ /**+ * Returns true if the frontend is online and connected to the server. Returns false if the internet connection is offline and not connected to the server.+ * + * @example+ * const isConnected = useIsConnected();+ */+ function useIsConnected(): boolean;++ interface ThinBackendProps {+ requireLogin?: boolean;+ children: JSX.Element[] | JSX.Element;+ }+ function ThinBackend(props: ThinBackendProps): JSX.Element;+ }+ |]+ + (generateTypeScriptTypeDefinitions schema) `shouldBe` expected++ describe "recordInterface" do+ it "should generate required fields for fields with default values" do+ let t = (table "tasks")+ { columns =+ [ (col "id" PUUID) { notNull = True }+ , (col "title" PText) { defaultValue = Just (TextExpression "untitled"), notNull = True }+ ]+ , primaryKeyConstraint = PrimaryKeyConstraint ["id"]+ }+ let expected = [trimming|+ interface Task {+ id: UUID;+ title: string;+ }+ |]+ (recordInterface t) `shouldBe` expected++ describe "newRcordInterface" do+ it "should generate optional fields for fields with default values" do+ let t = (table "tasks")+ { columns =+ [ (col "id" PUUID) { defaultValue = Just (CallExpression "uuid_generate_v4" []), notNull = True }+ , (col "title" PText) { defaultValue = Just (TextExpression "untitled"), notNull = True }+ ]+ , primaryKeyConstraint = PrimaryKeyConstraint ["id"]+ }+ let expected = [trimming|+ /**+ * A Task object not yet inserted into the `tasks` table+ */+ interface NewTask {+ id?: UUID;+ title?: string;+ }+ |]+ (newRecordInterface t) `shouldBe` expected++ describe "newRecordType" do+ it "should generate a type that maps record types to their New variant" do+ let tasks = (table "tasks") { primaryKeyConstraint = PrimaryKeyConstraint ["id"] } :: CreateTable+ let users = (table "users") { primaryKeyConstraint = PrimaryKeyConstraint ["id"] } :: CreateTable+ let projects = (table "projects") { primaryKeyConstraint = PrimaryKeyConstraint ["id"] } :: CreateTable++ let expected = [trimming|+ type NewRecord<Type> = Type extends User ? NewUser : (Type extends Task ? NewTask : (Type extends Project ? NewProject : (never)));+ |]+ (newRecordType [ users, tasks, projects ]) `shouldBe` expected++parseSqlStatements :: Text -> [Statement]+parseSqlStatements sql =+ case Megaparsec.runParser Parser.parseDDL "input" sql of+ Left parserError -> error (cs $ Megaparsec.errorBundlePretty parserError) -- For better error reporting in hspec+ Right statements -> statements
+ changelog.md view
@@ -0,0 +1,9 @@+# Changelog for `ihp-datasync-typescript`++## v1.5.0++- Add PostgreSQL table inheritance (`INHERITS`) support in TypeScript codegen++## v1.4.0++- Initial release as a standalone package
+ exe/GenerateDataSyncTypes.hs view
@@ -0,0 +1,27 @@+module Main where++import IHP.Prelude+import Main.Utf8 (withUtf8)+import qualified Data.Text.IO as Text+import qualified IHP.Postgres.Parser as Parser+import qualified IHP.DataSync.TypeScript.Compiler as Compiler++main :: IO ()+main = withUtf8 do+ (sqlPath, tsPath) <- decodeArgs+ errorOrSchema <- Parser.parseSqlFile (textToOsPath (cs sqlPath))++ case errorOrSchema of+ Left error -> fail (cs error)+ Right schema -> do+ let types = Compiler.generateTypeScriptTypeDefinitions schema++ Text.writeFile tsPath types++decodeArgs :: IO (String, String)+decodeArgs = do+ args <- getArgs++ case args of+ [sqlPath, tsPath] -> pure (cs sqlPath, cs tsPath)+ otherwise -> fail "Invalid usage: generate-datasync-types Schema.sql Schema.ts"
+ ihp-datasync-typescript.cabal view
@@ -0,0 +1,61 @@+cabal-version: 2.2+name: ihp-datasync-typescript+version: 1.5.0+synopsis: TypeScript code generation for IHP DataSync+description: Generates TypeScript type interfaces from the IHP Schema.sql+license: MIT+license-file: LICENSE+author: digitally induced GmbH+maintainer: support@digitallyinduced.com+homepage: https://ihp.digitallyinduced.com/+bug-reports: https://github.com/digitallyinduced/ihp/issues+copyright: (c) digitally induced GmbH+category: Database+build-type: Simple+extra-source-files: README.md, changelog.md++source-repository head+ type: git+ location: https://github.com/digitallyinduced/ihp.git++common shared-properties+ default-language: GHC2021+ default-extensions:+ OverloadedStrings+ , NoImplicitPrelude+ , ImplicitParams+ , DisambiguateRecordFields+ , DuplicateRecordFields+ , OverloadedLabels+ , DataKinds+ , QuasiQuotes+ , TypeFamilies+ , PackageImports+ , RecordWildCards+ , DefaultSignatures+ , FunctionalDependencies+ , PartialTypeSignatures+ , BlockArguments+ , LambdaCase+ , TemplateHaskell+ , OverloadedRecordDot+ ghc-options: -Werror=incomplete-patterns -Werror=unused-imports -Werror=missing-fields++library+ import: shared-properties+ hs-source-dirs: .+ exposed-modules: IHP.DataSync.TypeScript.Compiler+ build-depends: ihp, ihp-postgres-parser, neat-interpolation++executable generate-datasync-types+ import: shared-properties+ build-depends: ihp-datasync-typescript, ihp, ihp-postgres-parser, neat-interpolation, with-utf8, text+ hs-source-dirs: .+ main-is: exe/GenerateDataSyncTypes.hs++test-suite spec+ import: shared-properties+ type: exitcode-stdio-1.0+ hs-source-dirs: .+ main-is: Test/Spec.hs+ build-depends: ihp-datasync-typescript, ihp, ihp-postgres-parser, megaparsec, neat-interpolation, hspec