> ## Documentation Index
> Fetch the complete documentation index at: https://docs.regatta.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Running a TypeORM Application

Let's create a simple TypeORM application that queries the Regatta database. Start by importing the relevant classes from the `typeorm-regatta` package:

```javascript theme={null}
import { Column, DataSource, Entity, PrimaryColumn } from "typeorm-regatta"
```

Note that you should import all relevant classes based on the functionality of your application and its requirements.

## Connection Details

Connection parameters will be defined as follows:

```
const DB_HOST = "aaa.bbb.ccc.ddd:pppp";
const DB_USER = "MyUserName";
const DB_PASSWORD = "SomeSophisticatedPassword";
```

## Example Appliaction

To help you get acquainted with TypeORM on Regatta, we’ve provided a simple code example below.\
This application demonstrates common tasks such as defining entities, initializing a `DataSource`, inserting data, querying, updating, deleting, and cleaning up schema.

### Project Structure

Create the following folder structure:

```bash theme={null}
typeorm-example/
├── package.json
├── tsconfig.json
└── src/
    └── typeorm_example.ts
```

### Example Code

Create the main program and save it as: `src/typeorm_example.ts`

```typescript theme={null}
import { Column, DataSource, Entity, PrimaryColumn } from "typeorm-regatta"
import { v4 as uuidv4 } from "uuid" // Use uuid to generate unique ids
import type { QueryRunner } from "typeorm-regatta"

/**
 * Entity definition.
 * TypeORM will map this class to a "users" table.
 */
@Entity({ name: "users" })
class User {
    @PrimaryColumn()
    id!: string

    @Column()
    firstName!: string

    @Column()
    lastName!: string

    @Column()
    age!: number
}

/**
 * Connection details (replace with your own).
 * Note: In TypeORM-Regatta, host includes "<ip>:<port>".
 */
const DB_HOST = "aaa.bbb.ccc.ddd:pppp"
const DB_USER = "MyUserName"
const DB_PASSWORD = "SomeSophisticatedPassword"

/**
 * Create a new DataSource instance.
 * - `type: "regatta"` is provided by the typeorm-regatta package.
 * - `synchronize: true` tells TypeORM to create the schema automatically.
 * - `extra.deviceNames` is a Regatta-specific device mapping definition.
 */
const dataSource = new DataSource({
    type: "regatta",
    host: DB_HOST,
    username: DB_USER,
    password: DB_PASSWORD,
    entities: [User],
    synchronize: true,
    logging: true,
    extra: {
        deviceNames: ["m10d1"],
    },
})

async function run() {
    try {
        // Initialize the DataSource
        await dataSource.initialize()
        console.log("Data Source has been initialized!")

        const userRepository = dataSource.getRepository(User)

        // Create a new User
        const user = new User()
        user.id = uuidv4()
        user.firstName = "John"
        user.lastName = "Doe"
        user.age = 25

        // Insert
        await userRepository.save(user)
        console.log("User has been saved!")

        // Query
        const users = await userRepository.find()
        console.log("Users:", users)

        // Update
        user.age = 26
        await userRepository.save(user)
        console.log("User has been updated:", user)

        // Delete
        await userRepository.remove(user)
        console.log("User has been removed:", user)
    } catch (error) {
        console.error("Error:", error)
    } finally {
        // Drop the User table
        await dropUserTable()

        // Close the connection
        await dataSource.destroy()
    }
}

async function dropUserTable() {
    let queryRunner: QueryRunner | null = null

    try {
        queryRunner = dataSource.createQueryRunner()
        await queryRunner.connect()
        await queryRunner.startTransaction()

        // Drop the table created by @Entity() -> default table name is "user"
        await queryRunner.query('DROP TABLE "users"')
        console.log("User table has been dropped!")

        await queryRunner.commitTransaction()
    } catch (error) {
        console.error("Error dropping table:", error)
        if (queryRunner) {
            await queryRunner.rollbackTransaction()
        }
    } finally {
        if (queryRunner) {
            await queryRunner.release()
        }
    }
}

// Run the example app
run()
```

### TypeScript Configuration

Create `tsconfig.json` in the project root:

```json theme={null}
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "strict": true,
    "esModuleInterop": true,
    "experimentalDecorators": true,
    "strictPropertyInitialization": false,
    "emitDecoratorMetadata": true,
    "outDir": "./dist",
    "lib": ["ES2020", "DOM"],
    "typeRoots": ["./node_modules/@types"]
  },
  "include": ["src/typeorm_example.ts"]
}
```

### Package Setup

Create a `package.json` in the project root:

```json theme={null}
{
  "name": "typeorm-regatta-example",
  "version": "1.0.0",
  "private": true,
  "type": "commonjs",
  "scripts": {
    "build": "tsc",
    "start": "node dist/typeorm_example.js"
  },
  "dependencies": {
    "typeorm-regatta": "file:path/to/typeorm-regatta-<version>.tgz",
    "node-regatta": "file:path/to/node-regatta-<version>_<type>.tgz",
    "uuid": "^9.0.0",
    "reflect-metadata": "^0.2.0"
  },
  "devDependencies": {
    "typescript": "^5.3.3",
    "@types/node": "^18.13.0",
    "@types/uuid": "^9.0.0"
  }
}
```

<Note>
  This `package.json` assumes you already downloaded the [**Regatta TypeORM package and the Node.js driver**](/drivers-and-clients/javascript/install-your-javascript-client), and have them available on your local environment.

  Please ensure that you update the `package.json` file with the correct paths to the downloaded `.tgz` files before proceeding.
</Note>

## Running the Application

From the project root run:

```bash theme={null}
npm install
npm run build
npm start
```

Expected output:

```bash theme={null}
query: SHOW TABLES LIKE 'users'
query: CREATE TABLE SET NOT READY "users" ("id" varchar PRIMARY KEY INDEX WITH (devices = (m10d1)), "firstName" varchar NOT NULL, "lastName" varchar NOT NULL, "age" int8 NOT NULL) WITH (devices = (m10d1))
query: ALTER TABLE "users" SET READY
Data Source has been initialized!
query: SELECT "User"."id" AS "User_id", "User"."firstName" AS "User_firstName", "User"."lastName" AS "User_lastName", "User"."age" AS "User_age" FROM "users" "User" WHERE "User"."id" IN ($1) -- PARAMETERS: ["acaf5ed5-223d-40ae-8080-9196717cd54f"]
query: START TRANSACTION
query: INSERT INTO "users"("id", "firstName", "lastName", "age") VALUES ($1, $2, $3, $4) -- PARAMETERS: ["acaf5ed5-223d-40ae-8080-9196717cd54f","John","Doe",25]
query: COMMIT
User has been saved!
query: SELECT "User"."id" AS "User_id", "User"."firstName" AS "User_firstName", "User"."lastName" AS "User_lastName", "User"."age" AS "User_age" FROM "users" "User"
Users: [
  User {
    id: 'acaf5ed5-223d-40ae-8080-9196717cd54f',
    firstName: 'John',
    lastName: 'Doe',
    age: 25
  }
]
query: SELECT "User"."id" AS "User_id", "User"."firstName" AS "User_firstName", "User"."lastName" AS "User_lastName", "User"."age" AS "User_age" FROM "users" "User" WHERE "User"."id" IN ($1) -- PARAMETERS: ["acaf5ed5-223d-40ae-8080-9196717cd54f"]
query: START TRANSACTION
query: UPDATE "users" SET "age" = $1 WHERE "id" IN ($2) -- PARAMETERS: [26,"acaf5ed5-223d-40ae-8080-9196717cd54f"]
query: COMMIT
User has been updated: User {
  id: 'acaf5ed5-223d-40ae-8080-9196717cd54f',
  firstName: 'John',
  lastName: 'Doe',
  age: 26
}
query: SELECT "User"."id" AS "User_id", "User"."firstName" AS "User_firstName", "User"."lastName" AS "User_lastName", "User"."age" AS "User_age" FROM "users" "User" WHERE "User"."id" IN ($1) -- PARAMETERS: ["acaf5ed5-223d-40ae-8080-9196717cd54f"]
query: START TRANSACTION
query: DELETE FROM "users" WHERE "id" = $1 -- PARAMETERS: ["acaf5ed5-223d-40ae-8080-9196717cd54f"]
query: COMMIT
User has been removed: User { id: undefined, firstName: 'John', lastName: 'Doe', age: 26 }
query: START TRANSACTION
query: DROP TABLE "users"
User table has been dropped!
query: COMMIT
```
