Using rdb$get_context as default value for a column - dns

In a Firebird database, I need to create a DOMAIN with default value taken from the context variable.
It should be something like
CREATE DOMAIN USER_ID AS INTEGER
DEFAULT RDB$GET_CONTEXT('USER_SESSION','UID') NOT NULL;
When I execute this, I am getting the following error
Invalid token.
Dynamic SQL Error.
SQL error code = -104.
Token unknown - line 2, column 13.
RDB$GET_CONTEXT.
How can this be done, maybe there is another way than the DEFAULT clause?

Just create a BEFORE INSERT trigger:
CREATE TRIGGER your_trigger_name FOR your_table
BEFORE INSERT
POSITION 0
AS
BEGIN
IF (NEW.your_field IS NULL) THEN
NEW.your_field = RDB$GET_CONTEXT('USER_SESSION','UID');
END

Related

How to make the query work in linux server?

I have an database in PostgreSQL called "myDatabase" which has hundreds of schema and which is installed in Linux server. I am using this DB for an SAAS application. Which has multiple schema users. I want to update a column value in a table for selected schema
There is a particular column 'Percentage' in a table called 'sales' which i want to update the column value for all the existing users(Schema). So i have written a script to update the values in all schemas, this script is working in windows server but when i trying to execute this script in linux server, it shows an error
enter code hereThe below script i have written,
DO
$do$
DECLARE
_schema text;
BEGIN
FOR _schema IN
SELECT quote_ident(nspname) -- prevent SQL injection
FROM pg_namespace n
WHERE nspname !~~ 'pg_%' and nspname between 'schema1' and 'schema50'
AND nspname <> 'information_schema'
LOOP
EXECUTE 'SET LOCAL search_path = ' || _schema;
UPDATE sales SET sales.Percentage = 15;
END LOOP;
END
$do$
The above script is working in windows server but it is not working linux server. The error is given below
ERROR: column "sales" of relation "sales" does not exist
LINE 1: UPDATE sales SET sales.Percentage = 5
^
QUERY: UPDATE sales SET sales.Percentage = 5
CONTEXT: PL/pgSQL function inline_code_block line 10 at SQL statement
SQL state: 42703
Any help will be appreciated
Do not specify table name before the column name in the update:
UPDATE sales SET Percentage = 15
Here is the example that demonstrates this:
laika=# create table a (i integer);
CREATE TABLE
laika=# update a set a.i = 1;
ERROR: column "a" of relation "a" does not exist
LINE 1: update a set a.i = 1;
^
laika=# update a set i = 1;
UPDATE 0

Getting only the current authenticated user's data from an easy table/view in Azure

Using Microsoft Azure, I've created a database using easy tables (node.js backend). I have several tables and one view.
There's a trick to making the view work like an easy table which I've done.
Problem:
When using this code to read data from the view, I receive ALL data -- including data for other users.
table.read(function (context) {
return context.execute();
});
That makes sense, as I'm not specifying that I only want the authenticated user's data.
When using this code, I get NO data:
// READ operation
table.read(function (context) {
context.query.where({ userId: context.user.id });
return context.execute();
});
Using the above code for an actual table and not a view works perfectly.
From the log files:
2017-01-02T18:52:00.945Z - silly: Executing SQL statement SELECT TOP 3 * FROM [dbo].[ClassData] WHERE (([userId] = #p1) AND ([deleted] = #p2)); with parameters [{"name":"p1","pos":1,"value":"sid:REMOVED"},{"name":"p2","pos":2,"value":false}]
2017-01-02T18:52:00.945Z - silly: Read query returned 2 results
sprintf() will be removed in the next major release, use the sprintf-js package instead.
2017-01-02T18:52:01.867Z - silly: Executing SQL statement SELECT TOP 10 * FROM [dbo].[StacksNamesView] WHERE (([userId] = #p1) AND ([deleted] = #p2)) ORDER BY [createdAt]; with parameters [{"name":"p1","pos":1,"value":"sid:REMOVED"},{"name":"p2","pos":2,"value":false}]
2017-01-02T18:52:01.883Z - debug: SQL statement failed - Invalid column name 'userId'.: SELECT TOP 10 * FROM [dbo].[StacksNamesView] WHERE (([userId] = #p1) AND ([deleted] = #p2)) ORDER BY [createdAt]; with parameters [{"name":"p1","pos":1,"value":"sid:REMOVED"},{"name":"p2","pos":2,"value":false}]
UPDATE:
When creating Azure App Service EasyTables, the column "userId" is automatically a part of each table. However, it's not visible when looking at the schema via the Azure Portal. This is where my confusion was.
SOLUTION:
When using a view as an EasyTable and you need the "hidden" userId column, just make sure you select it as part of the view! This will work as long as your other EasyTables are executing queries such as the second block of code in this post.

Inserting data into database with python/sqlite3 by recognising the column name

I've got a problem that I don't know how to solve, I've tried many solutions but always getting that Operational error: near...
def insert_medicine_to_table():
con = sqlite3.connect('med_db3.db')
cur = con.cursor()
table_name = 'medicines'
column_name = "présentation"
value = 'Boîte de 2 seringues pré-remplies'
cur.execute("INSERT INTO medicines {} VALUES (?)".format(column_name), value)
con.commit()
con.close()
sqlite3.OperationalError: near "présentation": syntax error
The goal here is that either the script or python has to recognize the field (column name) and insert the value into "that" field, like the following:
fields = ['présentation', 'princeps', 'distributeur_ou_fabriquant', 'composition', 'famille', 'code_atc', 'ppv', 'prix_hospitalier', 'remboursement', 'base_de_remboursement__ppv', 'nature_du_produit']
values = ['Boîte de 2 seringues pré-remplies', 'Oui', 'SANOFI', 'Héparine', 'Anticoagulant héparinique', 'B01AB01', '43.80', '27.40', 'Oui', '43.80', 'Médicament']
That is one entry in the database. The problem here is that other entries can or not have one or more values for some field, and also the fields are not presented in the same order in other entries.
It has to recognize each field in the database table and insert each value into the right column.
The problem causing your error is that your SQL isn't valid. The statement you are trying to execute is:
INSERT INTO medicines présentation VALUES (?)
The statement you want to execute is:
INSERT INTO medicines ("présentation") VALUES (?)
As far as your larger question is concerned, if you create both the list of columns ("présentation") and list of parameter markers (?) and build the query using them, you're most of the way there.
If a field can have multiple values supplied for each "entry" in your database, you may need to change your database design to handle that. You'll at least need to figure out how you want to handle the situation, but that would be a matter for a different question.

SQL Azure Database / Can't Insert Record into a Table / ID not getting set during SubmitChanges

In the following instance, I have tried to simplify an issue to root components.
I've got a very simple SQL Azure database where I created a test table called Table1. Azure creates an ID field with Is Required, Is Primary Key checked. It will NOT allow to check the box Is Identity. There are a couple of other fields which are simply required.
In my VS2012 Project, I have created an LinqToSql Class which created a ProductionDataClasses1.dbml object.
I simply want to add a record to this table thru the method shown below. From what I am reading, ID would be set during the SubmitChanges() after InsertOnSubmit(NewRecord) is specified.
It does work the first time but value is set to zero. On subsequent save, I get an exception (basically it a duplicate record because ID=0 already exists).
To put this into context, I have included some sample code below. The idea is to first check if the record exists and update. If not, I want to add a record.
My question is... Do I need to manually set ID? If so, how do I set the value to an int and how to a retrieve the next value. I tried changing to a Guid but not allowed.
Here is my code sample:
public bool AddTestRecord(string someValue)
{
ProductionDataClasses1DataContext context = new ProductionDataClasses1DataContext();
try
{
var ExistingRecord = context.Table1s.SingleOrDefault(c => c.TextKey == someValue);
if (ExistingRecord == null)
{
var NewRecord = new Table1();
// NewRecord.ID = ???? ; How Do I Manually Set. It is getting set to 0 causing a duplicate value exception
NewRecord.TextKey = someValue;
NewRecord.AnotherValue = DateTime.Now.ToShortTimeString();
context.Table1s.InsertOnSubmit(NewRecord);
}
else
{
ExistingRecord.AnotherValue = DateTime.Now.TimeOfDay.ToString();
}
context.SubmitChanges();
return true;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return false;
context.SubmitChanges();
}
}
I would suggest manually running a SQL script to alter the table and make the column an identity. Look at this answer
Adding an identity to an existing column
Thanks for your reply.
I just was finally able to make this work on a new table and will try to follow along your instructions to make modifications to my real table. My code (as written above) was OK so the issue is in the SQL Azure table definition.
I found the issue is that when you create a new table in SQL Azure, it creates a table with three fields, ID, Column1, Column2. By default, ID is set as the Primary Key but none are checked as Is Identity.
To make this work, I made ID the Is Identity and unchecked PrimaryKey and Column1 the In Primary Key. Thus when a new record is saved, the ID is set and Column1 is checked to make sure it is not already in the system. I had to do this when the table was first created. Once saved, it would not allow me to change.
Afterwards, I updated my Linq To SQL class and dropped the new table in. I noted that now the AutoGenerated Value on ID and PrimaryKey on Column1 was set and my code worked.

How to deserialize DynamicComposite column value?

I am trying to implement a data model where row keys are Strings, column names are Longs and column values are DynamicComposites. Using Hector, an example of the stored procedure looks like this:
// create the value
DynamicComposite colVal = new DynamicComposite();
colVal.add(0, "someString");
colVal.setComparatorByPosition(0, "org.apache.cassandra.db.marshal.UTF8Type");
colVal.setSerializerByPosition(0, StringSerializer.get());
// create the column
HColumnImpl<Long, DynamicComposite> newCol = new
HColumnImpl<Long, DynamicComposite>(longSerializer,
dynamicCompositeSerializer);
newCol.setName(longValue);
newCol.setValue(colVal);
newCol.setClock(keySpace.createClock());
// insert the new column
Mutator<String> mutator = HFactory.createMutator(keySpace,stringSerializer);
mutator.addInsertion("rowKey","columnFamilyName",newCol);
mutator.execute();
Now, when I try to retrieve the data:
// create the query
SliceQuery<String,Long,DynamicComposite> sq =
HFactory.createSliceQuery(keySpace, stringSerializer, longSerializer,
dynamicCompositeSerializer);
// set the query
sq.setColumnFamily("columnFamilyName");
sq.setKey("rowKey");
sq.setColumnNames(longValue);
// execute the query
QueryResult<ColumnSlice<Long, DynamicComposite>> qr = sq.execute();
// get the data
qr.get().getColumnByName(longValue).getValue();
or when I just try to get plain byes:
// get the data
dynamicSerializer.fromByteBuffer(qr.get().
getColumnByName(longValue).getValueBytes());
I run into an exception:
Exception in thread "main" java.lang.NullPointerException
at com.google.common.base.Preconditions.checkNotNull(Preconditions.java:191)
at com.google.common.collect.ImmutableClassToInstanceMap.getInstance(ImmutableClassToInstanceMap.java:147)
at me.prettyprint.hector.api.beans.AbstractComposite.serializerForComparator(AbstractComposite.java:321)
at me.prettyprint.hector.api.beans.AbstractComposite.getSerializer(AbstractComposite.java:344)
at me.prettyprint.hector.api.beans.AbstractComposite.deserialize(AbstractComposite.java:713)
at me.prettyprint.hector.api.beans.DynamicComposite.fromByteBuffer(DynamicComposite.java:25)
at me.prettyprint.cassandra.serializers.DynamicCompositeSerializer.fromByteBuffer(DynamicCompositeSerializer.java:35)
As far as I have understood from all the tutorials I read, it should be possible to use DynamicComposite as column value. Therefore I want to ask: what am I doing wrong? From the exception it seems I am just forgetting to set something somewhere.
Radovan,
Its probably due to compatibility issues of the Guava library used in conjuction with the Hector version.
See also : https://github.com/hector-client/hector/pull/591
I am on Hector-core-1.1-1.jar, in combination with the Guava-14.0.jar I get the same error as you. When I use it with the Guava-12.0.1.jar however it works fine for me.

Resources