104 lines
2.2 KiB
JavaScript
104 lines
2.2 KiB
JavaScript
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,
|
|
},
|
|
// 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()
|
|
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
|
|
const tableExist = table[type](name)
|
|
references && onDelete
|
|
? tableExist.references(references).onDelete('CASCADE')
|
|
: tableExist.references(references)
|
|
})
|
|
})
|
|
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,
|
|
},
|
|
],
|
|
},
|
|
{
|
|
tableName: 'templates',
|
|
columns: [{ name: 'name', type: 'string' }],
|
|
},
|
|
{
|
|
tableName: 'codes',
|
|
columns: [
|
|
{
|
|
name: 'type_id',
|
|
type: 'string',
|
|
references: 'types.id',
|
|
onDelete: false,
|
|
},
|
|
{
|
|
name: 'template_id',
|
|
type: 'string',
|
|
references: 'templates.id',
|
|
onDelete: false,
|
|
},
|
|
{
|
|
name: 'title',
|
|
type: 'string',
|
|
},
|
|
{
|
|
name: 'description',
|
|
type: 'string',
|
|
},
|
|
{
|
|
name: 'code',
|
|
type: 'json',
|
|
},
|
|
{
|
|
name: 'preview',
|
|
type: 'text',
|
|
},
|
|
],
|
|
},
|
|
]
|
|
createTables(tables)
|
|
module.exports = {
|
|
knex,
|
|
}
|