Coder Social home page Coder Social logo

alex-shul / grunt-generate-database Goto Github PK

View Code? Open in Web Editor NEW

This project forked from sml-mirror/grunt-generate-database

0.0 1.0 0.0 264 KB

Grunt task to generate database script from models

License: MIT License

JavaScript 6.39% TypeScript 65.89% HTML 27.72%

grunt-generate-database's Introduction

grunt-generate-database

Build Status

Репозиторий, который хранит в себе плагин для создания DBWrapper, триггера и функции управления триггером с помощью typeorm и postgres

Установка

npm install grunt-generate-database

Как начать использовать

  • Создайте declaration.json в корневом каталоге
[
    {
      "db": "postgres",
      "name" : "base1",
      "dbtype" : "dbtype1",
      "dbhost" : "dbhost1",
      "dbport" : "dbport1",
      "dbusername" : "dbusername1",
      "dbpassword" : "dbpassword1",
      "dbdatabase" : "dbdatabase1",
      "pathToDBWrappers": "./dbscript",
      "schemas" : 
     [
       {
         "namespace": "testnamespace",
         "recreate":true,
         "tables":
         [
           {
             "name": "Class", 
             "pathToModel": "./models/class"
           }
         ]
       }
     ]
   }
 ]
  • Установите декораты на нужные модели.
import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";
import { GenerateHistory } from "grunt-generate-history-model";

@Entity()
@GenerateHistory({"historyPath": "./test/src/model/hero"})
export class Hero {
    @PrimaryGeneratedColumn()
    public id?: number;
    @Column()
    public name: string;
    public data: string;
    @Column()
    public detailId?: number;
    @Column({"type": "integer", "array": true, "nullable": true})
    public simpleArray: number[];
}
  • В package.json добавьте инициализирующую команду в свойство "scripts":
  "scripts": {
    "generation": "generateDatabase"
  }

где "generateDatabase" - строка для запуска плагина

  • npm run generation

  • после завершения работы плагина по пути, указанному в declaration.json в свойстве "pathToDBWrappers", появятся файлы с расширением ".ts" :

    • DBWrapper
import { Class } from '../../../models/class';
import { createbase1TriggerFuncstestnamespace } from './function';
import { createbase1Triggerstestnamespace } from './trigger';
import * as dotenv from 'dotenv';
import {createConnection, Connection, getManager, EntityManager} from 'typeorm';

export class testnamespaceDBWrapper {

   private static connection: Connection;

   public static async initialize(dropSchema?: boolean, sync?: boolean): Promise<void> {
       await this.close();

       if (! dropSchema) {
           dropSchema = false;
       }
       if (! sync) {
           sync = false;
       }

       this.connection = await this.createTables(dropSchema, sync);
       if (dropSchema) {
           await createbase1TriggerFuncstestnamespace();
           await createbase1Triggerstestnamespace();
       }
   }

   private static async createTables(dropSchema?: boolean, sync?: boolean) {
       return await createConnection({
           name: 'testnamespace',
           type: 'postgres',
           replication: {
               master: {
                   host:  process.env.dbhost1,
                   port: parseInt(process.env.dbport1, 10),
                   username:  process.env.dbusername1,
                   password: process.env.dbpassword1,
                   database: process.env.dbdatabase1
               },
               slaves: []
           },
           entities: [
           Class
],
     schema: 'testnamespace',
     synchronize: sync,
     dropSchema: dropSchema
     });
   }
   public static getEntityManager (): EntityManager {
       return getManager('testnamespace');
   }

   public static async close(): Promise<void> {
       if (this.connection) {
           await this.connection.close();
           this.connection = null;
       }
   }
}
  • Триггерная функция(пустая в примере в связи с отсутствием модели логирования)
import {createConnection, ConnectionOptions} from 'typeorm';


export async function createbase1TriggerFuncstestnamespace() {
const pgp = require('pg-promise')({});
await pgp.end();
const connectionString = 'postgres://' + process.env.dbusername1 + ':' +
process.env.dbpassword1 + '@' + process.env.dbhost1 + ':' + process.env.dbport1 + '/' + process.env.dbdatabase1;

const db = pgp(connectionString);
let queryproc = '';
pgp.end();

}
  • Триггер
import {createConnection, ConnectionOptions} from 'typeorm';


export async function createbase1Triggerstestnamespace() {
    const pgp = require('pg-promise')({});
    await pgp.end();
    const connectionString = 'postgres://' + process.env.dbusername1 + ':' +
    process.env.dbpassword1 + '@' + process.env.dbhost1 + ':' + process.env.dbport1 + '/' + process.env.dbdatabase1;
    const db = pgp(connectionString);
    let queryproc;
    let lowerStringName;
    let lowewrStringSchema;
    pgp.end();
}

Примечания к файлу конфигурации

  • Поле "db" имеет два значения : "mongo" и "postgres"
  • Значениями полей ,начинающихся с db(кроме поля "db") являются названия переменных в объекте process.env
  • Элементом массива является описание отдельной базы данных.
  • Свойства с префиксом db являются параметрами подключения к базе.
  • namespace отображает имя схемы в базе данных.
  • Массив tables показывает какие таблицы будут использоваться при работе со схемой.
  • У каждого элемента table существует опциональное поле historyPath, которое показывает есть ли у модели модель логирования.
  • Желательно для создания моделей логирования использовать npm пакет grunt-generate-history-model и его декораторы, а не созданные вручную модели логирования.
  • При использовании npm пакета для создания моделей логирования не обязательно указывать путь к моделям логирования в конфигурации.

grunt-generate-database's People

Contributors

godba11 avatar maxgorshkov avatar pavels111 avatar softmedialab avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.