I am looking how to create basic queries from Cloud SQL using App Script.
q1: "SELECT id FROM users WHERE name = 'some name';"
q2: "UPDATE users SET name = 'other name' WHERE id = 1;"
q3: "DELETE FROM users WHERE id = 1;"
I can read the entire table and insert data, however i cannot find the documentation on the google docs site for these types of queries.
I have tried using the query filter however it returns a bool not the ID INT, I am looking for.
var id =app.datasources.Users.query.filters.name._equals == "some name";
app.Pages.Page1.decendents.label1.text = id;
:>> Type mismatch: Cannot set type Boolean for property text. Type String is expected
Note: Users table sql equivelent (id INT AUTO_INCREMENT, name VARCHAR(64), PRIMARY KEY(id))
Your query server script syntax is wrong. Try
var query = app.models.Users.newQuery(); //new query
query.filters.name._equals = "some name"; //Note single`=`;
var records = query.run(); //run the query
app.Pages.Page1.decendents.label1.text = records[0].id;
To Read:
Query#run
Related
I am trying to create cache in Ignite using sql query
CacheConfiguration<?, ?> cacheCfg = new CacheConfiguration<>(DUMMY_CACHE_NAME);
IgniteCache<?, ?> cache = igniteInstance.getOrCreateCache(cacheCfg);
cache.query(new SqlFieldsQuery(
"CREATE TABLE IF NOT EXISTS MY_TABLE (id varchar, value varchar, PRIMARY KEY(id)) " +
"WITH \"template=replicated\", \"DATA_REGION=" + IgniteCacheConfiguration.DEFAULT_REGION + "\""));
Then I am trying to put some data into the cache using key-value api
IgniteCache<String, String> cache = ignite.cache("SQL_PUBLIC_MY_TABLE");
cache.put("1","example");
I know the data is stored successfully, I can retrieve it, I see that cache size is correct but when I am trying to retrieve the data with SQL
SELECT * FROM "PUBLIC".MY_TABLE
for example using DBeaver I am getting empty result
Do you know if it is how Ignite works or there is some additional configuration needed ?
By default, it wraps the kay and values in a class. You can tell it not to do that with the wrap_key and wrap_value parameter like this:
create table MY_TABLE (id varchar, value varchar, PRIMARY KEY(id)) with "wrap_key=false,wrap_value=false" ;
Suppose you have the following SQL Query to create a table called notes and store data in it :
CREATE TABLE notes (
id INTEGER PRIMARY KEY,
username TEXT,
token TEXT,
text TEXT
);
INSERT INTO notes (username, token, text) VALUES ('alice', 'token-a', 'Reminder: buy milk');
INSERT INTO notes (username, token, text) VALUES ('alice', 'token-a', 'I like Bob');
INSERT INTO notes (username, token, text) VALUES ('bob', 'token-b', 'TODO: write tests');
Now to attempt SQL injection to get all alice's notes without knowing her token where the query to get the data is given as :
'''SELECT text
FROM notes
WHERE token = '%s'
''' % token
What should be the text send in the variable token so as to perform SQL injection and get all alice's notes.
Try Something like this-
';SELECT text
FROM notes
WHERE username = 'alice
SQL Injection can be implemented by concatenating the SQL statement with the input parameters. For example, the following statement is vulnerable to SQL Injection:
String statement = "SELECT ID FROM USERS WHERE USERNAME = '" + inputUsername + "' AND PASSWORD = '" + hashedPassword + "'";
An attacker would enter a username like this:
' OR 1=1 Limit 1; --
Thus, the executed statement will be:
SELECT ID FROM USERS WHERE USERNAME = '' OR 1=1 Limit 1; --' AND PASSWORD = 'Blob'
Hence, the password part is commented, and the database engine would return any arbitrary result which will be acceptable by the application.
I found this nice explanation on the free preview of "Introduction to Cybersecurity for Software Developers" course.
https://www.udemy.com/course/cybersecurity-for-developers-1/
It also explains how to prevent SQL Injection.
Let's suppose we have a table defined with:
CREATE TABLE IF NOT EXISTS signals(sigid INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT)
This table initially is empty.
I would like to get the sigid for a given name with a select and in case name does not exist, add it and get the new autoincremented id.
I would like to use this query in order to autogenerate ,when needed, a new id that is used as foreign key in another table. I must put attention to the performances so I cannot proceed as :
check if name is present and return id witha a SELECT
if returned id is null create a new entry with an INSERT
get the new id again with a new SELECT
Is it possible do it with a single SELECT-like query ?
Thanks!
i think with an single select no.
Let's say i want to insert id_build = 3, hashed_value = 1 into the big table 'crash'.
The code in example makes first select to check if the value was already in the table, if yes skips the insert with where .. is null then retrive the id from already saved into temporary table.
example :
create temporary table if not exists Variablez(Name TEXT primary key on conflict replace, Value TEXT); --storing vars
insert into Variablez(Name, Value) values ('tmp_id', (select id_crash from crash where hashed_value = "1" )); --put id if was existing
insert into crash(id_build, hashed_value) select 3, 1 where (select Value from Variablez where Name = 'tmp_id' ) is null; -- insert if not exists
select
case
when (select Value from Variablez where name = 'tmp_id' ) is null then
'0'
else
'1'
end
as existing,
case
when (select Value from Variablez where name = 'tmp_id' ) is null then
(select id_crash from crash where hashed_value = "1")
else
(select Value from Variablez where name = 'tmp_id')
end
as id_returned;
if the table is empty and you are the one filling it in just one shot (and you don't need to do it again later on when there is data in the table), AND you don't have too many rows, then you could just cache the names you have already inserted and look them up in memory.
It's more of a comment, I guess.
there is also this for getting the last inserted id:
SELECT last_insert_rowid();
But if the above applies, you are even faster by assigning the ids yourself, and not define it as AUTOINCREMENT. Then you don't need to get the last inserted id, you just keep a counter and all the names inserted and increment for each new name you find.
CREATE TABLE IF NOT EXISTS signals(sigid INTEGER PRIMARY KEY NOT NULL, name TEXT)
List<String> insertedNames = new List<String>();
int count = 0;
while(input.hasNext())
{
String name = input.next();
if( !insertedNames.contains(name) )
{
var sql = "insert into table (sigid,name) VALUES (" + count + ", " + name + ")";
executeSql(sql);
insertedNames.add(name);
count++;
}
}
answering your comment
public int getId( string name )
{
String sql = "select id from table where name='" + name + "'";
int theIdForTheName = executeAndGetFirstColumnAsInt(sql);
return theIdForTheName;
}
i don't know what else to tell you...
I'm not able to update a table with Hibernate.
The table is created with the following statement and stored in a PostgreSQL Database.
CREATE TABLE staat
(
sta_id serial NOT NULL, -- ID des Staates
sta_bezeichnung character varying(50) NOT NULL, -- Langbezeichnung
sta_lkz character varying(10) NOT NULL, -- Laenderkennzeichen
sta_vorwahl character varying(10), -- Telefon Landesvorwahl
sta_eu boolean DEFAULT false, -- Ist der Staaat ein EU-Mitglied?
CONSTRAINT staat_pkey PRIMARY KEY (sta_id),
CONSTRAINT staat_sta_bezeichnung_key UNIQUE (sta_bezeichnung)
)
WITH (
OIDS=FALSE
);
Rights are set correct, because select, insert and update are possible with a SQL Manager. The following update statement also works with the SQL Manager.
But now the problem: when I want to update the table with my application, it generates PSQLException with the following output:
WARNUNG: SQL Error: 0, SQLState: 22004 and ERROR: query string argument of EXECUTE is null
The source code:
Query q = s.createQuery("Update Staat set sta_bezeichnung = 'BlaBla' where sta_id = 1");
int status = q.executeUpdate();
I think the problem has something to do with NOT NULL columns, because tables without NOT NULL columns can be updated with the same source code...
Does anyone has an idea of what is wrong or what I have to do???
Edit: tried with SQL (q.executeSQLUpdate) and HQL
Transaction tr = s.beginTransaction();
staat = (Staat)s.get(Staat.class, new Integer(0));
staat.setStaBezeichnung("BlaBla");
s.update(staat);
tr.commit();
Generates followin error: ERROR: query string argument of EXECUTE is null and Could not synchronize database state with session
Edit2: update works fine without hibernate
Please check your Hibernate mapping file for Staat maybe you have not configured a not-null constraint for some attribute/field, which is not-null in database.
It looks like you are trying to use SQL query where HQL query is expected. Try
Query q = s.createSQLQuery(....);
Or better yet, use mapped classes with HQL. But I don't know your mapped classes, so can't speculate on specifics.
I need to insert a record to a table.
Subsonic builds the query something like this (as far as i know):
INSERT INTO Table1
(Title, Description, RowVersion)
VALUES
(#Title, #Description, #RowVersion)
But i want to remove the RowVersion column from the SQL query bacause its autogenerated by the sql server.
How can i do that?
You don't need to worry about this. SubSonic is intelligent enough to handle this!
Just create new object assign values to properties and save it.
var o = new DataObject();
o.Name="Foo";
o.Age = 20;
//o.RowVersion = ....; DON'T ASSIGN THIS
o.Save();
EDIT:- Here is what I've tried:
Table Definition:
CREATE TABLE [dbo].[TestTimeStamp](
[RowID] [int] IDENTITY(1,1) NOT NULL PRIMARY KEY,
[Description] [nvarchar](50) NOT NULL,
[RowVersion] [timestamp] NOT NULL
)
Code:
private static void Test()
{
var o = new TestTimeStamp();
o.Description = "Hello World";
o.Save();
}
FIXED:- Yippe, I spinned my head over the cause, as this has never happened in SubSonic 2. I branched SubSonic 3 code, but there was not anything to find. Then after much fooling around I once again examined T4 templates. Some how the IsReadOnly property is not being set but it is checked when cretaing insert, update queries in SubSonic.Extension.Object.cs class. So the solution is to add a line to Structs.tt file's for loop which adds columns to table classes :) . To fix find the following loop (it starts at line 30)
<# foreach(var col in tbl.Columns){#>
Columns.Add(new DatabaseColumn("<#=col.Name#>", this)
{
and change initialization of new DatabaseColumn to as follows:
Columns.Add(new DatabaseColumn("<#=col.Name#>", this)
{
IsPrimaryKey = <#=col.IsPK.ToString().ToLower()#>,
DataType = DbType.<#=col.DbType.ToString()#>,
IsNullable = <#=col.IsNullable.ToString().ToLower()#>,
AutoIncrement = <#=col.AutoIncrement.ToString().ToLower()#>,
IsForeignKey = <#=col.IsForeignKey.ToString().ToLower()#>,
//THIS LINE DO THE TRICK.
IsReadOnly = <#=col.DataType.ToLower().Equals("timestamp")
.ToString().ToLower() #>
});
PS:- Please get subsonic srouce from here. In the previous version only null and AutoIncrement is checked on inclusion into Add and Update column list, but this code checks for ReadOnly property also.
I was having grief with timestamp fields so just excluded timestamp columns in Structs.tt altogether. Same place as above Line 30. This is using current SubSonic 3.0 master checkout
if(<#=col.DataType.ToLower().Equals("timestamp").ToString().ToLower() #>)
{}else{
Columns.Add(new DatabaseColumn("<#=col.Name#>", this)
{
IsPrimaryKey = <#=col.IsPK.ToString().ToLower()#>,
DataType = DbType.<#=col.DbType.ToString()#>,
IsNullable = <#=col.IsNullable.ToString().ToLower()#>,
AutoIncrement = <#=col.AutoIncrement.ToString().ToLower()#>,
IsForeignKey = <#=col.IsForeignKey.ToString().ToLower()#>,
MaxLength = <#=col.MaxLength#>
});
}