I'm running a pretty simple node js app that tracks user hits on a given website. The development version is working just fine writing to a SQL 2012 Enterprise Server, but the production version is getting the following error:
error running query { RequestError: The INSERT permission was denied on the object 'StudentMonitor', database 'LearnOnlineStatus', schema 'dbo'.
at StreamEvents.<anonymous> (C:\Node\MoodleMonitor\node_modules\mssql\lib\msnodesqlv8.js:624:21)
at StreamEvents.g (events.js:286:16)
at emitOne (events.js:96:13)
at StreamEvents.emit (events.js:188:7)
at routeStatementError (C:\Node\MoodleMonitor\node_modules\msnodesqlv8\lib\driverMgr.js:119:20)
at onInvoke (C:\Node\MoodleMonitor\node_modules\msnodesqlv8\lib\driverMgr.js:476:17)
at onQuery (C:\Node\MoodleMonitor\node_modules\msnodesqlv8\lib\driverMgr.js:157:17) name: 'RequestError', message: 'The INSERT permission was denied on the object \'StudentMonitor\', database \'LearnOnlineStatus\', schema \' dbo\'.', code: 'EREQUEST', number: 229, lineNumber: undefined, state: '42000', class: undefined, serverName: undefined, procName: undefined }
It's attempting to execute the following INSERT code:
mssql.getConnection(function(err, client, done) {
for (var i = 0; i < 7; i++) {
client.input('' + (i+1), data[i]);
}
client.query('INSERT INTO [dbo].[StudentMonitor] (time_created, user_id, ip, url, duration, page_title, course_id) VALUES (#1, #2, #3, #4, #5, #6, #7)', function(err, result) {
if(err) {
console.error('error running query', err);
}
// return the client to the connection pool for other requests to reuse
done();
return typeof callback === 'function' ? callback(err, result) : result;
});
});
All credentials listed in configurations are correct, and we've eliminated network issues as a symptom. Trying the insert statement via SQL Manager works fine with those credentials.
What drives me batty is that a select works just fine, and the user account we're using is DBOwner, so should have no issues whatsoever. Checking the table in SQL reveals no weird permissions or triggers, it's just a regular old table.
Currently running on two Windows 2012 (64-bit) R2 servers but the behaviour is the same on both. SQL Native Client 11.0 is installed, and I've added and removed ODBC clients with no impact. Credentials are set via a mssql.conf file that is all correct and confirmed from console logs. Any ideas?
Okay, was using trustedConnection:true with the mssql (lib/mssql.js) stuff, so it was using my credentials rather than the provided ones. Switching this out for false and adding user and password has resolved the issue.
Related
I'm able to successfully connect to the Snowflake database through my .NET app, but I'm unable to run a SQL command due to the following error from the Snowflake:
Message: Http status: UnprocessableEntity
ResponseContent:
"code" : "391920",
"message" : "Unable to run the command. You must specify the warehouse to use by either setting the warehouse field in the body of the request or by setting the DEFAULT_NAMESPACE property for the current user.",
"sqlState" : "57P03",
"statementHandle" : "01a8
Here is my code I'm using.
public async Task<QueryResult> QuerySnowflake(string statement, string database, string schema)
{
var content = new
{
statement,
database,
schema
};
return await _httpClient.SnowflakePost<QueryResult>($"https://{_accountId}.snowflakecomputing.com/api/v2/statements", content, await GetHeaders(), _cancellationToken);
}
statement = SELECT * FROM SNOWFLAKE_SAMPLE_DATA.TPCH_SF1.CUSTOMER
database = SNOWFLAKE_SAMPLE_DATA
schema = TPCH_SF1
I have already tried the following:
ALTER USER my_username SET DEFAULT_NAMESPACE = SNOWFLAKE_SAMPLE_DATA.TPCH_SF1
GRANT SELECT ON ALL TABLES IN SCHEMA "TPCH_SF1" TO ROLE sysadmin
ALTER USER my_username SET DEFAULT_ROLE = sysadmin
All of these did not change the error response.
I don't think it needs a code change as it works with other Snowflake accounts (I'm using a new trial account). I believe I have my something wrong with my account (e.g. missing role, missing warehouse, missing permission, etc).
Any help would be very much appreciated.
The user does not have a default warehouse and none is specified in the connection request or a use command in the session. You can try sending this command before running your select:
use warehouse MY_WAREHOUSE;
You can also specify it in the connection, or specify a default for the user:
ALTER USER MY_USER SET DEFAULT_WAREHOUSE = MY_WAREHOUSE;
After I triggered and refreshed the dag task, it went from running, delayed, to failed. The error log from the airflow told me to check the error from sql server which I got "Failed to start system task System Task" when I checked the logs on my sql server docker container. I'm not sure if I need to specify a schema but the rest of the connection params are correct.
[entrypoint.sh]
"${AIRFLOW_CONN_MY_SRC_DB:=mssql+pyodbc://SA:P#SSW0RD#mssqlcsc380:1433/?driver=ODBC+Driver+17+for+SQL+Server}"
[dag.py]
with DAG (
'mssql_380_dag',
start_date=days_ago(1),
schedule_interval=None,
catchup=False,
default_args={
'owner' : 'me',
'retries' : 1,
'retry_delay' : dt.timedelta(minutes=5)
}
) as dag:
get_requests = MsSqlOperator(
task_id = 'get_requests',
mssql_conn_id = 'my_src_db',
sql = 'select * from Request',
dag = dag
)
The issue was just that it couldn't notice the table so I specified the database which fixed the issue even though the database should of been recognized since I've passed it on the connection string.
sql = 'use csc380db; select * from Request',
I'm trying to assign securables against a user, but every time I try and grant permissions on a table-valued function, I get the error:
Key cannot be null.
Parameter name: key (mscorlib)
There is no error when adding stored procedures, views or tables, and using T-SQL to grant the permissions works fine. I've tried this on different databases on the same server and two instances of SQL Server 2016 with exactly the same errors.
SQL Server 2016 v13.0.4202.2
SSMS v16 build 13.0.15900.1
Edit: Upgrade to SSMS 17.1 build 14.0.17119.0 didn't help
As a side note (possibly related), I'm also getting an error when trying to list all objects belonging to a schema via User > Securables > Search > All objects belonging to the schema. It doesn't matter which schema I pick, the dialog closes with the error:
Value does not fall within the expected range. (SqlMgmt)
More information:
Stack trace from the "Technical details" button:
===================================
Key cannot be null.
Parameter name: key (mscorlib)
------------------------------
Program Location:
at System.Collections.Hashtable.ContainsKey(Object key)
at System.Collections.Hashtable.Contains(Object key)
at System.Collections.Specialized.HybridDictionary.Contains(Object key)
at Microsoft.SqlServer.Management.SqlMgmt.PermissionsData.SecurableColumnParent.ApplyRevokes(SqlSmoObject obj)
at Microsoft.SqlServer.Management.SqlMgmt.PermissionsData.Principal.ApplyChanges(String principalName, Server server)
at Microsoft.SqlServer.Management.SqlMgmt.PermissionsDatabasePrincipal.OnRunNow(Object sender)
at Microsoft.SqlServer.Management.SqlMgmt.PanelExecutionHandler.Run(RunType runType, Object sender)
at Microsoft.SqlServer.Management.SqlMgmt.SqlMgmtTreeViewControl.DoPreProcessExecutionAndRunViews(RunType runType)
at Microsoft.SqlServer.Management.SqlMgmt.SqlMgmtTreeViewControl.ExecuteForSql(PreProcessExecutionInfo executionInfo, ExecutionMode& executionResult)
at Microsoft.SqlServer.Management.SqlMgmt.SqlMgmtTreeViewControl.Microsoft.SqlServer.Management.SqlMgmt.IExecutionAwareSqlControlCollection.PreProcessExecution(PreProcessExecutionInfo executionInfo, ExecutionMode& executionResult)
at Microsoft.SqlServer.Management.SqlMgmt.ViewSwitcherControlsManager.RunNow(RunType runType, Object sender)
I'm running the SQL Server Copy Database Wizard.
Of note is that the Operator is NT AUTHORITY\SYSTEM, which I thought should have the authority to run whatever it wants.
How can we grant sufficient privileges to NT AUTHORITY\SYSTEM? I have already tried:
GRANT EXECUTE ON xp_regread TO public
GRANT EXECUTE ON xp_regread TO [NT AUTHORITY\SYSTEM]
And running the following shows that it worked.
SELECT
grantee_principal.name AS [Grantee]
, prmssn.permission_name
FROM
sys.all_objects AS xproc
INNER JOIN sys.database_permissions AS prmssn ON prmssn.major_id=xproc.object_id AND prmssn.minor_id=0 AND prmssn.class=1
INNER JOIN sys.database_principals AS grantee_principal ON grantee_principal.principal_id = prmssn.grantee_principal_id
WHERE
(xproc.type='X')and(xproc.name=N'xp_regread' and SCHEMA_NAME(xproc.schema_id)=N'sys')
Output:
Grantee permission_name
public EXECUTE
NT AUTHORITY\SYSTEM EXECUTE
The following error occurs:
Event Name: OnError
Message: An exception occurred while executing a Transact-SQL statement or batch.
StackTrace: at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(String sqlCommand, SqlCommand& command)
at Microsoft.SqlServer.Management.Smo.ExecuteSql.GetDataReader(String query, SqlCommand& command)
at Microsoft.SqlServer.Management.Smo.DataProvider.SetConnectionAndQuery(ExecuteSql execSql, String query)
at Microsoft.SqlServer.Management.Smo.ExecuteSql.GetDataProvider(StringCollection query, Object con, StatementBuilder sb, RetriveMode rm)
at Microsoft.SqlServer.Management.Smo.SqlObjectBase.FillData(ResultType resultType, StringCollection sql, Object connectionInfo, StatementBuilder sb)
at Microsoft.SqlServer.Management.Smo.SqlObjectBase.FillDataWithUseFailure(SqlEnumResult sqlresult, ResultType resultType)
at Microsoft.SqlServer.Management.Smo.SqlObjectBase.BuildResult(EnumResult result)
at Microsoft.SqlServer.Management.Smo.SqlServer.GetData(EnumResult erParent)
at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData()
at Microsoft.SqlServer.Management.Sdk.Sfc.Environment.GetData(Request req, Object ci)
at Microsoft.SqlServer.Management.Sdk.Sfc.Enumerator.GetData(Object connectionInfo, Request request)
at Microsoft.SqlServer.Management.Smo.ExecutionManager.GetEnumeratorDataReader(Request req)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.GetInitDataReader(String[] fields, OrderBy[] orderby)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.ImplInitialize(String[] fields, OrderBy[] orderby)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.Initialize(Boolean allProperties)
at Microsoft.SqlServer.Management.Smo.SqlSmoObject.OnPropertyMissing(String propname, Boolean useDefaultValue)
at Microsoft.SqlServer.Management.Smo.PropertyCollection.RetrieveProperty(Int32 index, Boolean useDefaultOnMissingValue)
at Microsoft.SqlServer.Management.Smo.PropertyCollection.GetValueWithNullReplacement(String propertyName, Boolean throwOnNullValue, Boolean useDefaultOnMissingValue)
at Microsoft.SqlServer.Management.Smo.Server.get_InstanceName()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.MappedLogin.RefreshData()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.MappedLogin.CheckDirty()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.GetDatabaseLogins()
at Microsoft.SqlServer.Dts.Tasks.TransferObjectsTask.TransferObjectsTask.UpdateObjectsToCopy()
InnerException-->xp_regread() returned error 5, 'Access is denied.'
xp_regread() returned error 5, 'Access is denied.'
xp_regread() returned error 5, 'Access is denied.'
StackTrace: at Microsoft.SqlServer.Management.Common.ConnectionManager.ExecuteTSql(ExecuteTSqlAction action, Object execObject, DataSet fillDataSet, Boolean catchException)
at Microsoft.SqlServer.Management.Common.ServerConnection.ExecuteReader(String sqlCommand, SqlCommand& command)
Operator: NT AUTHORITY\SYSTEM
Source Name: SQLSERVER2008R2_Transfer Objects Task
Source ID: {9D0562F4-FCC9-498D-A2A9-FC9E5F3B681B}
Execution ID: {23FF505D-00D3-4F84-8B9D-D9EC962C78D2}
Start Time: 2015-04-17 7:23:24 PM
End Time: 2015-04-17 7:23:24 PM
Data Code: 0
This is the tool we need to use, because we don't have access to the remote server, and because the Import-Export Wizard failed.
You might need to add the account to the sysadmin server role, which allows a member to perform every activity.
For 2008r2, execute this command:
EXEC sp_addsrvrolemember 'NT AUTHORITY\SYSTEM', 'sysadmin';
This is a common error encountered when attempting to update the registry from SQL Server, and there are some weird and non-obvious pathing issues in newer versions such as SQL Server 2017.
The error is not due to security within SQL Server, but instead Windows security related to the permissions on the registry keys as relates to the users under which specific SQL Server processes are running.
For instance, to execute MSSQL related registry commands from SQL Server, the system group NETWORKSERVICE needs full control on the relevant registry path. This is because SQL Agent (by default) runs as a user in that system group.
For SQL Server settings, the Registry path is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server
As an example, the command in SQL Server to set the log file size limit to be 1024 KB is as follows:
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE',
N'SOFTWARE\Microsoft\Microsoft SQL Server\MSSQLServer',
N'ErrorLogSizeInKb', REG_DWORD, 1024
GO
Also note the truncated path above. The actual full registry path (for SQL2017) is as follows:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQLServer
The xp_instance_regwrite SQL Server command automatically injects the version key into the path. For SQL Server 2017 that key is MSSQL14.MSSQLSERVER.
I have some strange issue with querying SQL Server from django.
When I query db twice in single request, I got errors in some cases. Namely when first db query returns big amount of data, we end up with error while querying db second time.
Details:
We're using Microsoft SQL Server backend for Django (https://bitbucket.org/Manfre/django-mssql/src) running on windows.
We want allow user to filter data from some table ("Activity") via form, display it on the website's table and then show related data from another table ("Frames") on map.
class Frames(models.Model):
...
class Activity(models.Model):
frame_from = models.ForeignKey(Frames, ...)
...
The problem is: when we want to filter larger amount of data from Activity (let's say 200rows x 6 colums), we can not make other queries in the same request on table Frames (MARS is turned on in Django settings.py):
result = Aktywnosci.objects.filter(qset1)
is always ok, but
path = Frames.objects.filter(qset2)
when the previous query returned larger amount of data, raises OLE DB Error:
'Microsoft OLE DB Provider for SQL Server' Error: Cannot
create new connection because in manual or distributed transaction mode.
PS. Database settings from settings.py:
# Database for this installation.
DATABASES = {
'default':{
'ENGINE': 'django.db.backends.sqlserver_ado',
'NAME': '***',
'USER': '***',
'PASSWORD': '***',
'HOST': '***',
'PORT': '',
'OPTIONS' : {
'provider': 'SQLOLEDB',
'use_mars': True,
}
}
}
PS2. I came across this issue on the google-code page of djang-mssql: http://code.google.com/p/django-mssql/issues/detail?id=79 - but it seems to be solved in new version of package...
What can I do about it?
Thanks in advance
We got the solution at bitbucket: https://bitbucket.org/Manfre/django-mssql/issue/13/ole-db-provider-for-sql-server-error from Michael Manfre - thanks a lot for this.
The solution is following:
"SQLOLEDB and MARS doesn't work very well and I intend on changing all of the documentation and defaults to assume a native client driver will be used. Try using the native client; "SQLNCLI10" or "SQLNCLI11".
DATABASES = {
'default': {
'ENGINE': 'sqlserver_ado',
'NAME': 'mydb',
'HOST': r'localhost',
'USER': '',
'PASSWORD': '',
'OPTIONS': {
'provider': 'SQLNCLI10',
'extra_params': 'DataTypeCompatibility=80;MARS Connection=True;',
},
}
}
Is "use_mars=True" set up in your "settings.py" file?
http://django-mssql.readthedocs.org/en/latest/settings.html
If this doesn't work, I have a question: is your selection in SQL Server involving tables with triggers on them (transact SQL scripts) - in this case the SQL Server will use a static cursor instead of a firehose one (which is what you need) therefore you will get your error. Try to get rid of the triggers, use some views in SQL Server and select from them instead of tables.