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

# create.db.ts

Verifica si existe la base de datos, la crea si es necesario, habilita la extensión `pg_trgm` y sincroniza las tablas de Drizzle usando `drizzle-kit push`.

```typescript create.db.ts theme={null}
import { execSync } from 'child_process';
import { Client } from 'pg';
import { dbConfig } from './config.db';

async function createDatabase() {
  const { database, ...postgresConfig } = dbConfig;

  // Connect to default 'postgres' database to check/create the target database
  const client = new Client({
    ...postgresConfig,
    database: 'postgres',
  });

  try {
    await client.connect();

    const result = await client.query(`SELECT 1 FROM pg_database WHERE datname = $1`, [database]);

    if (result.rowCount === 0) {
      console.log(`Database '${database}' does not exist. Creating...`);
      await client.query(`CREATE DATABASE "${database}"`);
      console.log(`✅ Database '${database}' created successfully.`);
    } else {
      console.log(`Database '${database}' already exists.`);
    }
  } catch (error) {
    console.error('❌ Error checking/creating database:', error);
    process.exit(1);
  } finally {
    await client.end();
  }
}

async function enableExtensions() {
  const { database, ...postgresConfig } = dbConfig;
  const client = new Client({
    ...postgresConfig,
    database: database,
  });

  try {
    await client.connect();
    await client.query('CREATE EXTENSION IF NOT EXISTS pg_trgm;');
    console.log("✅ Extension 'pg_trgm' enabled successfully.");
  } catch (error) {
    console.error('❌ Error enabling extensions:', error);
    throw error;
  } finally {
    await client.end();
  }
}

async function createTables() {
  try {
    await createDatabase();
    await enableExtensions();
    execSync('npx drizzle-kit push --config=drizzle.config.ts', {
      stdio: 'inherit',
      cwd: process.cwd(),
    });
    console.log('✅ Tablas creadas exitosamente desde los modelos');
    process.exit(0);
  } catch (error) {
    console.error('❌ Error al crear las tablas/extensions');
    process.exit(1);
  }
}

createTables();
```

## Ejecución

```bash Terminal theme={null}
npm run db:create
```

**Importante:** `drizzle-kit push` puede modificar el esquema existente. Revisa los cambios y realiza un respaldo antes de ejecutarlo sobre bases de datos con información.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.