expressSandbox/PG/knex.js

104 lines
2.2 KiB
JavaScript
Raw Normal View History

2024-12-09 10:00:39 +00:00
const knex = require('knex')({
client: 'pg',
connection: {
host: 'yhm.ink',
user: 'postgres',
password: '123456',
database: 'sandbox',
port: 54321,
},
pool: {
min: 2,
max: 10,
idleTimeoutMillis: 30000,
createTimeoutMillis: 3000,
acquireTimeoutMillis: 30000,
},
2024-12-09 10:00:39 +00:00
// connection:`postgres://postgres:123456@yhm.ink:54321/sandbox`
})
async function createTableIfNotExist({ tableName, columns }) {
const exists = await knex.schema.hasTable(tableName)
if (!exists) {
await knex.schema.createTable(tableName, (table) => {
tableName === 'codes'
? table.increments('id').primary()
: table.string('id').primary()
2024-12-09 10:00:39 +00:00
table.timestamp('created_at').defaultTo(knex.fn.now())
table.timestamp('updated_at').defaultTo(knex.fn.now())
columns.forEach((column) => {
const { name, type, references, onDelete } = column
2024-12-09 10:00:39 +00:00
const tableExist = table[type](name)
references && onDelete
? tableExist.references(references).onDelete('CASCADE')
: tableExist.references(references)
2024-12-09 10:00:39 +00:00
})
})
console.log(`table ${tableName} created`)
} else {
console.log(`table ${tableName} exists`)
}
}
async function createTables(tables) {
for (const table of tables) {
await createTableIfNotExist(table)
}
}
const tables = [
{
tableName: 'types',
columns: [
{ name: 'name', type: 'string' },
{
name: 'parent_id',
type: 'string',
references: 'types.id',
onDelete: false,
},
2024-12-09 10:00:39 +00:00
],
},
{
tableName: 'templates',
columns: [{ name: 'name', type: 'string' }],
},
2024-12-09 10:00:39 +00:00
{
tableName: 'codes',
columns: [
{
name: 'type_id',
type: 'string',
2024-12-09 10:00:39 +00:00
references: 'types.id',
onDelete: false,
},
{
name: 'template_id',
type: 'string',
references: 'templates.id',
onDelete: false,
2024-12-09 10:00:39 +00:00
},
{
name: 'title',
type: 'string',
},
{
name: 'description',
type: 'string',
},
{
name: 'code',
type: 'json',
},
{
name: 'preview',
type: 'text',
},
],
},
]
createTables(tables)
module.exports = {
knex,
}