plugin-postgresql-connector
Version:
NocoBase plugin for connecting to external PostgreSQL databases
145 lines (138 loc) • 3.4 kB
text/typescript
import { DataTypes, Model } from 'sequelize';
import { Database } from '@nocobase/database';
export class Connection extends Model {
static init(database: Database) {
super.init({
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
name: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
validate: {
notEmpty: true,
len: [1, 100],
},
},
host: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
},
},
port: {
type: DataTypes.INTEGER,
defaultValue: 5432,
validate: {
min: 1,
max: 65535,
},
},
database: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
len: [1, 63],
},
},
username: {
type: DataTypes.STRING,
allowNull: false,
validate: {
notEmpty: true,
len: [1, 63],
},
},
password: {
type: DataTypes.TEXT, // Encrypted password
allowNull: false,
validate: {
notEmpty: true,
},
},
ssl: {
type: DataTypes.BOOLEAN,
defaultValue: false,
},
isActive: {
type: DataTypes.BOOLEAN,
defaultValue: true,
},
connectionOptions: {
type: DataTypes.JSON,
defaultValue: {},
},
createdAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
},
updatedAt: {
type: DataTypes.DATE,
defaultValue: DataTypes.NOW,
},
}, {
sequelize: database.sequelize,
modelName: 'Connection',
tableName: 'postgresql_connections',
timestamps: true,
paranoid: true, // Soft delete
indexes: [
{
unique: true,
fields: ['name'],
where: {
deletedAt: null,
},
},
{
fields: ['isActive'],
},
],
});
}
static associate(models: any) {
this.hasMany(models.SavedQuery, {
foreignKey: 'connectionId',
as: 'savedQueries',
onDelete: 'CASCADE',
});
}
// Instance methods
public async testConnection(): Promise<boolean> {
// This will be implemented in service layer
return true;
}
public getConnectionConfig(): object {
return {
host: this.getDataValue('host'),
port: this.getDataValue('port'),
database: this.getDataValue('database'),
username: this.getDataValue('username'),
password: this.getDataValue('password'), // Will be decrypted in service
ssl: this.getDataValue('ssl'),
connectionOptions: this.getDataValue('connectionOptions'),
};
}
// Hide sensitive data in JSON
public toJSON(): object {
const values = { ...this.get() };
delete values.password;
return values;
}
}
export default Connection;
export interface ConnectionConfig {
name: string;
host: string;
port: number;
database: string;
username: string;
password: string;
ssl: boolean;
connectionOptions?: Record<string, any>;
}