Browse Source

Update MssqlClient.ts

pull/4477/head
Naude555 2 years ago committed by GitHub
parent
commit
b15d3dc1b0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 470
      packages/nocodb/src/lib/db/sql-client/lib/mssql/MssqlClient.ts

470
packages/nocodb/src/lib/db/sql-client/lib/mssql/MssqlClient.ts

@ -183,7 +183,7 @@ class MssqlClient extends KnexClient {
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
await this.sqlClient.raw('SELECT 1+1 as data'); await this.sqlClient.raw('SELECT 1+1 AS data');
} catch (e) { } catch (e) {
log.ppe(e); log.ppe(e);
result.code = -1; result.code = -1;
@ -246,7 +246,7 @@ class MssqlClient extends KnexClient {
try { try {
const rows = await this.sqlClient.raw( const rows = await this.sqlClient.raw(
`SELECT SERVERPROPERTY('productversion') as version, SERVERPROPERTY ('productlevel') as level, SERVERPROPERTY ('edition') as edition, @@version as versionD` `SELECT SERVERPROPERTY('productversion') AS version, SERVERPROPERTY ('productlevel') AS level, SERVERPROPERTY ('edition') AS edition, @@version AS versionD`
); );
result.data.object = {}; result.data.object = {};
@ -284,7 +284,7 @@ class MssqlClient extends KnexClient {
const tempSqlClient = knex(connectionParamsWithoutDb); const tempSqlClient = knex(connectionParamsWithoutDb);
const rows = await tempSqlClient.raw( const rows = await tempSqlClient.raw(
`select name from sys.databases where name = '${args.database}'` `SELECT name from sys.databases WHERE name = '${args.database}'`
); );
if (rows.length === 0) { if (rows.length === 0) {
@ -356,14 +356,12 @@ class MssqlClient extends KnexClient {
try { try {
/** ************** START : create _evolution table if not exists *************** */ /** ************** START : create _evolution table if not exists *************** */
const exists = await this.sqlClient.schema const exists = await this.sqlClient.schema.withSchema(this.schema).hasTable(args.tn);
.withSchema(this.schema)
.hasTable(args.tn);
if (!exists) { if (!exists) {
await this.sqlClient.schema await this.sqlClient.schema.withSchema(this.schema).createTable(
.withSchema(this.schema) args.tn,
.createTable(args.tn, function (table) { function (table) {
table.increments(); table.increments();
table.string('title').notNullable(); table.string('title').notNullable();
table.string('titleDown').nullable(); table.string('titleDown').nullable();
@ -373,7 +371,8 @@ class MssqlClient extends KnexClient {
table.integer('status').nullable(); table.integer('status').nullable();
table.dateTime('created'); table.dateTime('created');
table.timestamps(); table.timestamps();
}); }
);
log.debug('Table created:', `${this.getTnPath(args.tn)}`); log.debug('Table created:', `${this.getTnPath(args.tn)}`);
} else { } else {
log.debug(`${this.getTnPath(args.tn)} tables exists`); log.debug(`${this.getTnPath(args.tn)} tables exists`);
@ -395,9 +394,7 @@ class MssqlClient extends KnexClient {
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
result.data.value = await this.sqlClient.schema result.data.value = await this.sqlClient.schema.withSchema(this.schema).hasTable(args.tn);
.withSchema(this.schema)
.hasTable(args.tn);
} catch (e) { } catch (e) {
log.ppe(e, _func); log.ppe(e, _func);
throw e; throw e;
@ -415,7 +412,7 @@ class MssqlClient extends KnexClient {
try { try {
const rows = await this.sqlClient.raw( const rows = await this.sqlClient.raw(
`select name from sys.databases where name = '${args.databaseName}'` `SELECT name FROM sys.databases WHERE name = '${args.databaseName}'`
); );
result.data.value = rows.length > 0; result.data.value = rows.length > 0;
} catch (e) { } catch (e) {
@ -441,7 +438,7 @@ class MssqlClient extends KnexClient {
try { try {
result.data.list = await this.sqlClient.raw( result.data.list = await this.sqlClient.raw(
`SELECT name as database_name, database_id, create_date from sys.databases order by name` `SELECT name AS database_name, database_id, create_date FROM sys.databases ORDER BY name`
); );
} catch (e) { } catch (e) {
log.ppe(e, _func); log.ppe(e, _func);
@ -466,8 +463,8 @@ class MssqlClient extends KnexClient {
try { try {
result.data.list = await this.sqlClient.raw( result.data.list = await this.sqlClient.raw(
`select schema_name(t.schema_id) as schema_name, `SELECT schema_name(t.schema_id) AS schema_name,
t.name as tn, t.create_date, t.modify_date from sys.tables t WHERE schema_name(t.schema_id) = ? order by schema_name,tn `, t.name AS tn, t.create_date, t.modify_date FROM sys.tables t WHERE schema_name(t.schema_id) = ? ORDER BY schema_name,tn `,
[this.schema || 'dbo'] [this.schema || 'dbo']
); );
} catch (e) { } catch (e) {
@ -487,7 +484,7 @@ class MssqlClient extends KnexClient {
try { try {
result.data.list = await this.sqlClient.raw( result.data.list = await this.sqlClient.raw(
`SELECT name as schema_name FROM master.${this.schema}.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb');` `SELECT name AS schema_name FROM master.${this.schema}.sysdatabases WHERE name not in ('master', 'tempdb', 'model', 'msdb');`
); );
} catch (e) { } catch (e) {
log.ppe(e, _func); log.ppe(e, _func);
@ -535,53 +532,53 @@ class MssqlClient extends KnexClient {
try { try {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw(`select const response = await this.sqlClient.raw(`SELECT
c.table_name as tn, c.table_name AS tn,
case WHEN trg1.trigger_name IS NULL THEN CAST(0 as BIT) ELSE CAST(1 as BIT) END as au, CASE WHEN trg1.trigger_name IS NULL THEN CAST(0 AS BIT) ELSE CAST(1 AS BIT) END AS au,
c.column_name as cn, c.column_name AS cn,
c.ordinal_position as cop, c.ordinal_position AS cop,
pk.constraint_type as ck, pk.constraint_type AS ck,
case WHEN COLUMNPROPERTY(object_id(CONCAT('${this.schema}.', c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') = 1 CASE WHEN COLUMNPROPERTY(object_id(CONCAT('${this.schema}.', c.TABLE_NAME)), c.COLUMN_NAME, 'IsIdentity') = 1
THEN THEN
1 1
ELSE ELSE
0 0
END as ai, END AS ai,
c.is_nullable as nrqd, c.is_nullable AS nrqd,
c.data_type as dt, c.data_type AS dt,
c.column_default as cdf,c.character_maximum_length as clen, c.column_default AS cdf,c.character_maximum_length AS clen,
c.character_octet_length,c.numeric_precision as np,c.numeric_scale as ns,c.datetime_precision as dp,c.character_set_name as csn, c.character_octet_length,c.numeric_precision AS np,c.numeric_scale AS ns,c.datetime_precision AS dp,c.character_set_name AS csn,
c.collation_name as clnn, c.collation_name AS clnn,
pk.constraint_type as cst, pk.ordinal_position as op, pk.constraint_name as pk_constraint_name, pk.constraint_type AS cst, pk.ordinal_position AS op, pk.constraint_name AS pk_constraint_name,
fk.parent_table as rtn, fk.parent_column as rcn, fk.parent_table AS rtn, fk.parent_column AS rcn,
v.table_name as is_view, v.table_name AS is_view,
df.default_constraint_name df.default_constraint_name
from information_schema.columns c FROM INFORMATION_SCHEMA.COLUMNS c
left join left join
( select kc.constraint_name, kc.table_name,kc.column_name, kc.ordinal_position,tc.constraint_type ( SELECT kc.constraint_name, kc.table_name,kc.column_name, kc.ordinal_position,tc.constraint_type
from information_schema.key_column_usage kc FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE kc
inner join information_schema.table_constraints as tc INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS tc
on kc.constraint_name = tc.constraint_name and tc.constraint_type in ('primary key') ON kc.constraint_name = tc.constraint_name AND tc.constraint_type in ('primary key')
where kc.table_catalog='${args.databaseName}' and kc.table_schema='${this.schema}' WHERE kc.table_catalog='${args.databaseName}' AND kc.table_schema='${this.schema}'
) pk ) pk
on ON
pk.table_name = c.table_name and pk.column_name=c.column_name pk.table_name = c.table_name AND pk.column_name=c.column_name
left join left join
( select ( SELECT
ccu.table_name as child_table ccu.table_name AS child_table
,ccu.column_name as child_column ,ccu.column_name AS child_column
,kcu.table_name as parent_table ,kcu.table_name AS parent_table
,kcu.column_name as parent_column ,kcu.column_name AS parent_column
,ccu.constraint_name ,ccu.constraint_name
from information_schema.constraint_column_usage ccu FROM INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE ccu
inner join information_schema.referential_constraints rc INNER JOIN INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
on ccu.constraint_name = rc.constraint_name ON ccu.constraint_name = rc.constraint_name
inner join information_schema.key_column_usage kcu INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE kcu
on kcu.constraint_name = rc.unique_constraint_name ) fk ON kcu.constraint_name = rc.unique_constraint_name ) fk
on ON
fk.child_table = c.table_name and fk.child_column=c.column_name fk.child_table = c.table_name AND fk.child_column=c.column_name
left join information_schema.views v left join INFORMATION_SCHEMA.VIEWS v
on v.table_name=c.table_name ON v.table_name=c.table_name
left join ( left join (
SELECT SELECT
default_constraints.name default_constraint_name, all_columns.name name default_constraints.name default_constraint_name, all_columns.name name
@ -598,17 +595,17 @@ class MssqlClient extends KnexClient {
ON all_columns.default_object_id = default_constraints.object_id ON all_columns.default_object_id = default_constraints.object_id
WHERE WHERE
schemas.name = '${this.schema}' schemas.name = '${this.schema}'
AND tables.name = '${args.tn}') df on df.name = c.column_name AND tables.name = '${args.tn}') df ON df.name = c.column_name
left join ( select trg.name as trigger_name, left join ( SELECT trg.name AS trigger_name,
tab.name as [table1] tab.name AS [table1]
from sys.triggers trg FROM sys.triggers trg
left join sys.objects tab left join sys.objects tab
on trg.parent_id = tab.object_id ON trg.parent_id = tab.object_id
where tab.name = '${args.tn}') trg1 on trg1.trigger_name = CONCAT('xc_trigger_${args.tn}_' , c.column_name) WHERE tab.name = '${args.tn}') trg1 ON trg1.trigger_name = CONCAT('xc_trigger_${args.tn}_' , c.column_name)
where c.table_catalog='${args.databaseName}' and c.table_schema='${this.schema}' and c.table_name = '${args.tn}' WHERE c.table_catalog='${args.databaseName}' AND c.table_schema='${this.schema}' AND c.table_name = '${args.tn}'
order by c.table_name, c.ordinal_position`); ORDER BY c.table_name, c.ordinal_position`);
for (let i = 0; i < response.length; i++) { for (let i = 0; i < response.length; i++) {
const el = response[i]; const el = response[i];
@ -660,39 +657,39 @@ class MssqlClient extends KnexClient {
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`select t.[name] as table_view, `SELECT t.[name] AS table_view,
case when t.[type] = 'U' then 'Table' CASE WHEN t.[type] = 'U' THEN 'Table'
when t.[type] = 'V' then 'View' WHEN t.[type] = 'V' THEN 'View'
end as [object_type], END AS [object_type],
i.index_id, i.index_id,
case when i.is_primary_key = 1 then 'Primary key' CASE WHEN i.is_primary_key = 1 THEN 'Primary key'
when i.is_unique = 1 then 'Unique' WHEN i.is_unique = 1 THEN 'Unique'
else 'Not Unique' end as [type], else 'Not Unique' END AS [type],
i.[name] as index_name, i.[name] AS index_name,
substring(column_names, 1, len(column_names)-1) as [columns], substring(column_names, 1, len(column_names)-1) AS [columns],
case when i.[type] = 1 then 'Clustered index' CASE WHEN i.[type] = 1 THEN 'Clustered index'
when i.[type] = 2 then 'Nonclustered unique index' WHEN i.[type] = 2 THEN 'Nonclustered unique index'
when i.[type] = 3 then 'XML index' WHEN i.[type] = 3 THEN 'XML index'
when i.[type] = 4 then 'Spatial index' WHEN i.[type] = 4 THEN 'Spatial index'
when i.[type] = 5 then 'Clustered columnstore index' WHEN i.[type] = 5 THEN 'Clustered columnstore index'
when i.[type] = 6 then 'Nonclustered columnstore index' WHEN i.[type] = 6 THEN 'Nonclustered columnstore index'
when i.[type] = 7 then 'Nonclustered hash index' WHEN i.[type] = 7 THEN 'Nonclustered hash index'
end as index_type END AS index_type
from sys.objects t FROM sys.objects t
inner join sys.indexes i INNER JOIN sys.indexes i
on t.object_id = i.object_id ON t.object_id = i.object_id
cross apply (select col.[name] + ',' + CAST(ic.key_ordinal as varchar) + ',' cross apply (SELECT col.[name] + ',' + CAST(ic.key_ordinal AS varchar) + ','
from sys.index_columns ic FROM sys.index_columns ic
inner join sys.columns col INNER JOIN sys.columns col
on ic.object_id = col.object_id ON ic.object_id = col.object_id
and ic.column_id = col.column_id AND ic.column_id = col.column_id
where ic.object_id = t.object_id WHERE ic.object_id = t.object_id
and ic.index_id = i.index_id AND ic.index_id = i.index_id
order by col.column_id ORDER BY col.column_id
for xml path ('') ) D (column_names) for xml path ('') ) D (column_names)
where t.is_ms_shipped <> 1 WHERE t.is_ms_shipped <> 1
and index_id > 0 and t.name = '${this.getTnPath(args.tn)}' AND index_id > 0 AND t.name = '${this.getTnPath(args.tn)}'
order by schema_name(t.schema_id) + '.' + t.[name], i.index_id` ORDER BY schema_name(t.schema_id) + '.' + t.[name], i.index_id`
); );
const rows = []; const rows = [];
for (let i = 0, rowCount = 0; i < response.length; ++i, ++rowCount) { for (let i = 0, rowCount = 0; i < response.length; ++i, ++rowCount) {
@ -751,39 +748,39 @@ class MssqlClient extends KnexClient {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`select t.[name] as table_view, `SELECT t.[name] AS table_view,
case when t.[type] = 'U' then 'Table' CASE WHEN t.[type] = 'U' THEN 'Table'
when t.[type] = 'V' then 'View' WHEN t.[type] = 'V' THEN 'View'
end as [object_type], END AS [object_type],
i.index_id, i.index_id,
case when i.is_primary_key = 1 then 'Primary key' CASE WHEN i.is_primary_key = 1 THEN 'Primary key'
when i.is_unique = 1 then 'Unique' WHEN i.is_unique = 1 THEN 'Unique'
else 'Not Unique' end as [type], else 'Not Unique' END AS [type],
i.[name] as index_name, i.[name] AS index_name,
substring(column_names, 1, len(column_names)-1) as [columns], substring(column_names, 1, len(column_names)-1) AS [columns],
case when i.[type] = 1 then 'Clustered index' CASE WHEN i.[type] = 1 THEN 'Clustered index'
when i.[type] = 2 then 'Nonclustered unique index' WHEN i.[type] = 2 THEN 'Nonclustered unique index'
when i.[type] = 3 then 'XML index' WHEN i.[type] = 3 THEN 'XML index'
when i.[type] = 4 then 'Spatial index' WHEN i.[type] = 4 THEN 'Spatial index'
when i.[type] = 5 then 'Clustered columnstore index' WHEN i.[type] = 5 THEN 'Clustered columnstore index'
when i.[type] = 6 then 'Nonclustered columnstore index' WHEN i.[type] = 6 THEN 'Nonclustered columnstore index'
when i.[type] = 7 then 'Nonclustered hash index' WHEN i.[type] = 7 THEN 'Nonclustered hash index'
end as index_type END AS index_type
from sys.objects t FROM sys.objects t
inner join sys.indexes i INNER JOIN sys.indexes i
on t.object_id = i.object_id ON t.object_id = i.object_id
cross apply (select col.[name] + ', ' + CAST(ic.key_ordinal as varchar) + ', ' cross apply (SELECT col.[name] + ', ' + CAST(ic.key_ordinal AS varchar) + ', '
from sys.index_columns ic FROM sys.index_columns ic
inner join sys.columns col INNER JOIN sys.columns col
on ic.object_id = col.object_id ON ic.object_id = col.object_id
and ic.column_id = col.column_id AND ic.column_id = col.column_id
where ic.object_id = t.object_id WHERE ic.object_id = t.object_id
and ic.index_id = i.index_id AND ic.index_id = i.index_id
order by col.column_id ORDER BY col.column_id
for xml path ('') ) D (column_names) for xml path ('') ) D (column_names)
where t.is_ms_shipped <> 1 WHERE t.is_ms_shipped <> 1
and index_id > 0 and t.name = '${this.getTnPath(args.tn)}' AND index_id > 0 AND t.name = '${this.getTnPath(args.tn)}'
order by schema_name(t.schema_id) + '.' + t.[name], i.index_id` ORDER BY schema_name(t.schema_id) + '.' + t.[name], i.index_id`
); );
const rows = []; const rows = [];
for (let i = 0, rowCount = 0; i < response.length; ++i, ++rowCount) { for (let i = 0, rowCount = 0; i < response.length; ++i, ++rowCount) {
@ -841,25 +838,25 @@ class MssqlClient extends KnexClient {
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
const response = await this.sqlClient const response = await this.sqlClient
.raw(`select fk_tab.name as tn, '>-' as rel, pk_tab.name as rtn, .raw(`SELECT fk_tab.name AS tn, '>-' AS rel, pk_tab.name AS rtn,
fk_cols.constraint_column_id as no, fk_col.name as cn, ' = ' as [join], fk_cols.constraint_column_id AS no, fk_col.name AS cn, ' = ' AS [join],
pk_col.name as rcn, fk.name as cstn, pk_col.name AS rcn, fk.name AS cstn,
fk.update_referential_action_desc as ur, fk.delete_referential_action_desc as dr fk.update_referential_action_desc AS ur, fk.delete_referential_action_desc AS dr
from sys.foreign_keys fk FROM sys.foreign_keys fk
inner join sys.tables fk_tab INNER JOIN sys.tables fk_tab
on fk_tab.object_id = fk.parent_object_id ON fk_tab.object_id = fk.parent_object_id
inner join sys.tables pk_tab INNER JOIN sys.tables pk_tab
on pk_tab.object_id = fk.referenced_object_id ON pk_tab.object_id = fk.referenced_object_id
inner join sys.foreign_key_columns fk_cols INNER JOIN sys.foreign_key_columns fk_cols
on fk_cols.constraint_object_id = fk.object_id ON fk_cols.constraint_object_id = fk.object_id
inner join sys.columns fk_col INNER JOIN sys.columns fk_col
on fk_col.column_id = fk_cols.parent_column_id ON fk_col.column_id = fk_cols.parent_column_id
and fk_col.object_id = fk_tab.object_id AND fk_col.object_id = fk_tab.object_id
inner join sys.columns pk_col INNER JOIN sys.columns pk_col
on pk_col.column_id = fk_cols.referenced_column_id ON pk_col.column_id = fk_cols.referenced_column_id
and pk_col.object_id = pk_tab.object_id AND pk_col.object_id = pk_tab.object_id
where fk_tab.name = '${this.getTnPath(args.tn)}' WHERE fk_tab.name = '${this.getTnPath(args.tn)}'
order by fk_tab.name, pk_tab.name, fk_cols.constraint_column_id`); ORDER BY fk_tab.name, pk_tab.name, fk_cols.constraint_column_id`);
const ruleMapping = { const ruleMapping = {
NO_ACTION: 'NO ACTION', NO_ACTION: 'NO ACTION',
@ -907,24 +904,24 @@ class MssqlClient extends KnexClient {
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
const response = await this const response = await this
.raw(`select fk_tab.name as tn, '>-' as rel, pk_tab.name as rtn, .raw(`SELECT fk_tab.name AS tn, '>-' AS rel, pk_tab.name AS rtn,
fk_cols.constraint_column_id as no, fk_col.name as cn, ' = ' as [join], fk_cols.constraint_column_id AS no, fk_col.name AS cn, ' = ' AS [join],
pk_col.name as rcn, fk.name as cstn, pk_col.name AS rcn, fk.name AS cstn,
fk.update_referential_action_desc as ur, fk.delete_referential_action_desc as dr fk.update_referential_action_desc AS ur, fk.delete_referential_action_desc AS dr
from sys.foreign_keys fk FROM sys.foreign_keys fk
inner join sys.tables fk_tab INNER JOIN sys.tables fk_tab
on fk_tab.object_id = fk.parent_object_id ON fk_tab.object_id = fk.parent_object_id
inner join sys.tables pk_tab INNER JOIN sys.tables pk_tab
on pk_tab.object_id = fk.referenced_object_id ON pk_tab.object_id = fk.referenced_object_id
inner join sys.foreign_key_columns fk_cols INNER JOIN sys.foreign_key_columns fk_cols
on fk_cols.constraint_object_id = fk.object_id ON fk_cols.constraint_object_id = fk.object_id
inner join sys.columns fk_col INNER JOIN sys.columns fk_col
on fk_col.column_id = fk_cols.parent_column_id ON fk_col.column_id = fk_cols.parent_column_id
and fk_col.object_id = fk_tab.object_id AND fk_col.object_id = fk_tab.object_id
inner join sys.columns pk_col INNER JOIN sys.columns pk_col
on pk_col.column_id = fk_cols.referenced_column_id ON pk_col.column_id = fk_cols.referenced_column_id
and pk_col.object_id = pk_tab.object_id AND pk_col.object_id = pk_tab.object_id
order by fk_tab.name, pk_tab.name, fk_cols.constraint_column_id`); ORDER BY fk_tab.name, pk_tab.name, fk_cols.constraint_column_id`);
const ruleMapping = { const ruleMapping = {
NO_ACTION: 'NO ACTION', NO_ACTION: 'NO ACTION',
@ -972,31 +969,31 @@ class MssqlClient extends KnexClient {
const result = new Result(); const result = new Result();
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
const query = `select trg.name as trigger_name, const query = `SELECT trg.name AS trigger_name,
tab.name as [table], tab.name AS [table],
case when is_instead_of_trigger = 1 then 'Instead of' CASE WHEN is_instead_of_trigger = 1 THEN 'Instead of'
else 'After' end as [activation], else 'After' END AS [activation],
(case when objectproperty(trg.object_id, 'ExecIsUpdateTrigger') = 1 (CASE WHEN objectproperty(trg.object_id, 'ExecIsUpdateTrigger') = 1
then 'Update' else '' end THEN 'Update' else '' end
+ case when objectproperty(trg.object_id, 'ExecIsDeleteTrigger') = 1 + CASE WHEN objectproperty(trg.object_id, 'ExecIsDeleteTrigger') = 1
then 'Delete' else '' end THEN 'Delete' else '' end
+ case when objectproperty(trg.object_id, 'ExecIsInsertTrigger') = 1 + CASE WHEN objectproperty(trg.object_id, 'ExecIsInsertTrigger') = 1
then 'Insert' else '' end THEN 'Insert' else '' end
) as [event], ) AS [event],
case when trg.parent_class = 1 then 'Table trigger' CASE WHEN trg.parent_class = 1 THEN 'Table trigger'
when trg.parent_class = 0 then 'Database trigger' WHEN trg.parent_class = 0 THEN 'Database trigger'
end [class], END [class],
case when trg.[type] = 'TA' then 'Assembly (CLR) trigger' CASE WHEN trg.[type] = 'TA' THEN 'Assembly (CLR) trigger'
when trg.[type] = 'TR' then 'SQL trigger' WHEN trg.[type] = 'TR' THEN 'SQL trigger'
else '' end as [type], else '' END AS [type],
case when is_disabled = 1 then 'Disabled' CASE WHEN is_disabled = 1 THEN 'Disabled'
else 'Active' end as [status], else 'Active' END AS [status],
object_definition(trg.object_id) as [definition] object_definition(trg.object_id) AS [definition]
from sys.triggers trg FROM sys.triggers trg
left join sys.objects tab left join sys.objects tab
on trg.parent_id = tab.object_id ON trg.parent_id = tab.object_id
where tab.name = '${this.getTnPath(args.tn)}' WHERE tab.name = '${this.getTnPath(args.tn)}'
order by trg.name;`; ORDER BY trg.name;`;
const response = await this.sqlClient.raw(query); const response = await this.sqlClient.raw(query);
@ -1041,7 +1038,7 @@ class MssqlClient extends KnexClient {
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`SELECT o.name as function_name,definition, o.create_date as created, o.modify_date as modified,o.* `SELECT o.name AS function_name,definition, o.create_date AS created, o.modify_date AS modified,o.*
FROM sys.sql_modules AS m FROM sys.sql_modules AS m
JOIN sys.objects AS o ON m.object_id = o.object_id JOIN sys.objects AS o ON m.object_id = o.object_id
AND type IN ('FN', 'IF', 'TF')` AND type IN ('FN', 'IF', 'TF')`
@ -1086,8 +1083,8 @@ class MssqlClient extends KnexClient {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`select SPECIFIC_NAME as procedure_name, ROUTINE_TYPE as [type],LAST_ALTERED as modified, CREATED as created,ROUTINE_DEFINITION as definition ,pc.* `SELECT SPECIFIC_NAME AS procedure_name, ROUTINE_TYPE AS [type],LAST_ALTERED AS modified, CREATED AS created,ROUTINE_DEFINITION AS definition ,pc.*
from ${args.databaseName}.information_schema.routines as pc where routine_type = 'PROCEDURE'` FROM ${args.databaseName}.INFORMATION_SCHEMA.ROUTINES AS pc WHERE routine_type = 'PROCEDURE'`
); );
result.data.list = response; result.data.list = response;
@ -1119,8 +1116,8 @@ class MssqlClient extends KnexClient {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`SELECT v.name as view_name,v.*,m.* FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id `SELECT v.name AS view_name,v.*,m.* FROM sys.views v INNER JOIN sys.schemas s ON s.schema_id = v.schema_id
inner join sys.sql_modules as m on m.object_id = v.object_id` INNER JOIN sys.sql_modules AS m ON m.object_id = v.object_id`
); );
result.data.list = response; result.data.list = response;
@ -1153,10 +1150,10 @@ class MssqlClient extends KnexClient {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`SELECT o.name as function_name,definition as create_function, o.create_date as created, o.modify_date as modified,o.* `SELECT o.name AS function_name,definition AS create_function, o.create_date AS created, o.modify_date AS modified,o.*
FROM sys.sql_modules AS m FROM sys.sql_modules AS m
JOIN sys.objects AS o ON m.object_id = o.object_id JOIN sys.objects AS o ON m.object_id = o.object_id
AND type IN ('FN', 'IF', 'TF') and o.name = '${args.function_name}'` AND type IN ('FN', 'IF', 'TF') AND o.name = '${args.function_name}'`
); );
for (let i = 0; i < response.length; i++) { for (let i = 0; i < response.length; i++) {
@ -1194,8 +1191,8 @@ class MssqlClient extends KnexClient {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`select SPECIFIC_NAME as procedure_name, ROUTINE_TYPE as [type],LAST_ALTERED as modified, CREATED as created,ROUTINE_DEFINITION as create_procedure ,pc.* `SELECT SPECIFIC_NAME AS procedure_name, ROUTINE_TYPE AS [type],LAST_ALTERED AS modified, CREATED AS created,ROUTINE_DEFINITION AS create_procedure ,pc.*
from ${args.databaseName}.information_schema.routines as pc where routine_type = 'PROCEDURE' and SPECIFIC_NAME='${args.procedure_name}'` FROM ${args.databaseName}.INFORMATION_SCHEMA.ROUTINES AS pc WHERE routine_type = 'PROCEDURE' AND SPECIFIC_NAME='${args.procedure_name}'`
); );
result.data.list = response; result.data.list = response;
@ -1224,8 +1221,8 @@ class MssqlClient extends KnexClient {
args.databaseName = this.connectionConfig.connection.database; args.databaseName = this.connectionConfig.connection.database;
const response = await this.sqlClient.raw( const response = await this.sqlClient.raw(
`SELECT v.name as view_name,v.*,m.*, m.definition as view_definition FROM sys.views v inner join sys.schemas s on s.schema_id = v.schema_id `SELECT v.name AS view_name,v.*,m.*, m.definition AS view_definition FROM sys.views v INNER JOIN sys.schemas s ON s.schema_id = v.schema_id
inner join sys.sql_modules as m on m.object_id = v.object_id where v.name = '${args.view_name}'` INNER JOIN sys.sql_modules AS m ON m.object_id = v.object_id WHERE v.name = '${args.view_name}'`
); );
result.data.list = response; result.data.list = response;
@ -1259,9 +1256,9 @@ class MssqlClient extends KnexClient {
FROM sysobjects AS [so] FROM sysobjects AS [so]
INNER JOIN sys.sql_modules AS df ON object_id = so.id INNER JOIN sys.sql_modules AS df ON object_id = so.id
INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id INNER JOIN sysobjects AS so2 ON so.parent_obj = so2.Id
WHERE [so].[type] = 'TR' and so2.name = '${this.getTnPath( WHERE [so].[type] = 'TR' AND so2.name = '${this.getTnPath(
args.tn args.tn
)}' and [so].[name] = '${args.trigger_name}'` )}' AND [so].[name] = '${args.trigger_name}'`
); );
for (let i = 0; i < response.length; i++) { for (let i = 0; i < response.length; i++) {
@ -1291,7 +1288,7 @@ class MssqlClient extends KnexClient {
try { try {
const rows = await this.sqlClient.raw( const rows = await this.sqlClient.raw(
`select name from sys.databases where name = '${args.database_name}'` `SELECT name FROM sys.databases WHERE name = '${args.database_name}'`
); );
if (rows.length === 0) { if (rows.length === 0) {
@ -1346,8 +1343,7 @@ class MssqlClient extends KnexClient {
log.api(`${func}:args:`, args); log.api(`${func}:args:`, args);
// `DROP TRIGGER ${args.trigger_name}` // `DROP TRIGGER ${args.trigger_name}`
try { try {
const query = `${this.querySeparator()}DROP TRIGGER IF EXISTS ${ const query = `${this.querySeparator()}DROP TRIGGER IF EXISTS ${args.trigger_name
args.trigger_name
}`; }`;
await this.sqlClient.raw(query); await this.sqlClient.raw(query);
@ -1478,8 +1474,7 @@ class MssqlClient extends KnexClient {
{ {
sql: sql:
this.querySeparator() + this.querySeparator() +
`DROP FUNCTION IF EXISTS ${ `DROP FUNCTION IF EXISTS ${args.function_name
args.function_name
};${this.querySeparator()}\n${args.create_function}`, };${this.querySeparator()}\n${args.create_function}`,
}, },
], ],
@ -1487,8 +1482,7 @@ class MssqlClient extends KnexClient {
{ {
sql: sql:
this.querySeparator() + this.querySeparator() +
`DROP FUNCTION IF EXISTS ${ `DROP FUNCTION IF EXISTS ${args.function_name
args.function_name
};${this.querySeparator()} ${args.oldCreateFunction}`, };${this.querySeparator()} ${args.oldCreateFunction}`,
}, },
], ],
@ -1560,8 +1554,7 @@ class MssqlClient extends KnexClient {
{ {
sql: sql:
this.querySeparator() + this.querySeparator() +
`DROP PROCEDURE IF EXISTS ${ `DROP PROCEDURE IF EXISTS ${args.procedure_name
args.procedure_name
};${this.querySeparator()}\n${args.create_procedure}`, };${this.querySeparator()}\n${args.create_procedure}`,
}, },
], ],
@ -1569,8 +1562,7 @@ class MssqlClient extends KnexClient {
{ {
sql: sql:
this.querySeparator() + this.querySeparator() +
`DROP PROCEDURE IF EXISTS ${ `DROP PROCEDURE IF EXISTS ${args.procedure_name
args.procedure_name
};${this.querySeparator()}${args.oldCreateProcedure}`, };${this.querySeparator()}${args.oldCreateProcedure}`,
}, },
], ],
@ -1599,7 +1591,7 @@ class MssqlClient extends KnexClient {
log.api(`${func}:args:`, args); log.api(`${func}:args:`, args);
try { try {
const query = this.genQuery( const query = this.genQuery(
`CREATE TRIGGER ?? on ?? \n${args.timing} ${args.event}\n as\n${args.statement}`, `CREATE TRIGGER ?? ON ?? \n${args.timing} ${args.event}\n as\n${args.statement}`,
[args.trigger_name, this.getTnPath(args.tn)] [args.trigger_name, this.getTnPath(args.tn)]
); );
await this.sqlClient.raw(query); await this.sqlClient.raw(query);
@ -1635,8 +1627,7 @@ class MssqlClient extends KnexClient {
try { try {
// await this.sqlClient.raw(`DROP TRIGGER ${args.trigger_name}`); // await this.sqlClient.raw(`DROP TRIGGER ${args.trigger_name}`);
await this.sqlClient.raw( await this.sqlClient.raw(
`ALTER TRIGGER ${args.trigger_name} ON ${this.getTnPath(args.tn)} \n${ `ALTER TRIGGER ${args.trigger_name} ON ${this.getTnPath(args.tn)} \n${args.timing
args.timing
} ${args.event}\n AS\n${args.statement}` } ${args.event}\n AS\n${args.statement}`
); );
@ -1721,8 +1712,7 @@ class MssqlClient extends KnexClient {
{ {
sql: sql:
this.querySeparator() + this.querySeparator() +
`DROP VIEW ${args.view_name} ; ${this.querySeparator()}${ `DROP VIEW ${args.view_name} ; ${this.querySeparator()}${args.oldViewDefination
args.oldViewDefination
};`, };`,
}, },
], ],
@ -1817,10 +1807,7 @@ class MssqlClient extends KnexClient {
const downStatement = const downStatement =
this.querySeparator() + this.querySeparator() +
this.sqlClient.schema this.sqlClient.schema.withSchema(this.schema).dropTable(args.table).toString();
.withSchema(this.schema)
.dropTable(args.table)
.toString();
this.emit(`Success : ${upQuery}`); this.emit(`Success : ${upQuery}`);
@ -1861,16 +1848,8 @@ class MssqlClient extends KnexClient {
AS AS
BEGIN BEGIN
SET NOCOUNT ON; SET NOCOUNT ON;
UPDATE ?? Set ?? = GetDate() where ?? in (SELECT ?? FROM Inserted) UPDATE ?? Set ?? = GetDate() WHERE ?? in (SELECT ?? FROM Inserted)
END;`, END;`, [triggerName, this.getTnPath(args.table_name), this.getTnPath(args.table_name), column.column_name, pk.column_name, pk.column_name]
[
triggerName,
this.getTnPath(args.table_name),
this.getTnPath(args.table_name),
column.column_name,
pk.column_name,
pk.column_name,
]
); );
upQuery += triggerCreateQuery; upQuery += triggerCreateQuery;
@ -1905,7 +1884,7 @@ class MssqlClient extends KnexClient {
AS AS
BEGIN BEGIN
SET NOCOUNT ON; SET NOCOUNT ON;
UPDATE [${this.schema}].[${args.table_name}] Set [${column.column_name}] = GetDate() where [${pk.column_name}] in (SELECT [${pk.column_name}] FROM Inserted) UPDATE [${this.schema}].[${args.table_name}] Set [${column.column_name}] = GetDate() WHERE [${pk.column_name}] in (SELECT [${pk.column_name}] FROM Inserted)
END;`; END;`;
upQuery += triggerCreateQuery; upQuery += triggerCreateQuery;
@ -2072,10 +2051,7 @@ class MssqlClient extends KnexClient {
/** ************** create up & down statements *************** */ /** ************** create up & down statements *************** */
const upStatement = const upStatement =
this.querySeparator() + this.querySeparator() +
this.sqlClient.schema this.sqlClient.schema.withSchema(this.schema).dropTable(args.tn).toString();
.withSchema(this.schema)
.dropTable(args.tn)
.toString();
let downQuery = this.querySeparator() + this.createTable(args.tn, args); let downQuery = this.querySeparator() + this.createTable(args.tn, args);
this.emit(`Success : ${upStatement}`); this.emit(`Success : ${upStatement}`);
@ -2089,9 +2065,8 @@ class MssqlClient extends KnexClient {
for (const relation of relationsList) { for (const relation of relationsList) {
downQuery += downQuery +=
this.querySeparator() + this.querySeparator() +
(await this.sqlClient (await this.sqlClient.withSchema(this.schema).schema
.withSchema(this.schema) .table(relation.tn, (table) => {
.schema.table(relation.tn, (table) => {
table = table table = table
.foreign(relation.cn, null) .foreign(relation.cn, null)
.references(relation.rcn) .references(relation.rcn)
@ -2134,8 +2109,7 @@ class MssqlClient extends KnexClient {
)) { )) {
downQuery += downQuery +=
this.querySeparator() + this.querySeparator() +
this.sqlClient.schema this.sqlClient.schema.withSchema(this.schema)
.withSchema(this.schema)
.table(tn, function (table) { .table(tn, function (table) {
if (non_unique) { if (non_unique) {
table.index(columns, key_name); table.index(columns, key_name);
@ -2180,9 +2154,7 @@ class MssqlClient extends KnexClient {
try { try {
const self = this; const self = this;
await this.sqlClient.schema.table( await this.sqlClient.schema.table(this.getTnPath(args.childTable), function (table) {
this.getTnPath(args.childTable),
function (table) {
table = table table = table
.foreign(args.childColumn, foreignKeyName) .foreign(args.childColumn, foreignKeyName)
.references(args.parentColumn) .references(args.parentColumn)
@ -2194,8 +2166,7 @@ class MssqlClient extends KnexClient {
if (args.onDelete) { if (args.onDelete) {
table = table.onDelete(args.onDelete); table = table.onDelete(args.onDelete);
} }
} });
);
const upStatement = const upStatement =
this.querySeparator() + this.querySeparator() +
@ -2256,12 +2227,9 @@ class MssqlClient extends KnexClient {
try { try {
const self = this; const self = this;
await this.sqlClient.schema.table( await this.sqlClient.schema.table(this.getTnPath(args.childTable), function (table) {
this.getTnPath(args.childTable),
function (table) {
table.dropForeign(args.childColumn, foreignKeyName); table.dropForeign(args.childColumn, foreignKeyName);
} });
);
const upStatement = const upStatement =
this.querySeparator() + this.querySeparator() +
@ -2404,7 +2372,7 @@ class MssqlClient extends KnexClient {
const result = new Result(); const result = new Result();
log.api(`${_func}:args:`, args); log.api(`${_func}:args:`, args);
try { try {
result.data = `DELETE FROM ${this.getTnPath(args.tn)} where ;`; result.data = `DELETE FROM ${this.getTnPath(args.tn)} WHERE ;`;
} catch (e) { } catch (e) {
log.ppe(e, _func); log.ppe(e, _func);
throw e; throw e;

Loading…
Cancel
Save