How to translate this snippet of executable pseudo code into ABAP?
phone_numbers = {
'hans': '++498912345',
'peter': '++492169837',
'alice': '++6720915',
}
# access
print (phone_numbers['hans'])
# add
phone_numbers['bernd']='++3912345'
# update
phone_numbers['bernd']='++123456'
if 'alice' in phone_numbers:
print('Yes, alice is known')
# all entries
for name, number in phone_numbers.items():
print(name, number)
Modern ABAP is possible up to 752, less chars, more upvotes :-)
P.S. BTW, up to now no one has added abap to pleac (Programming Language Examples Alike Cookbook)
Well, how about the following solution?
REPORT ZZZ.
TYPES: BEGIN OF t_phone_number,
name TYPE char40,
number TYPE char40,
END OF t_phone_number.
DATA: gt_phone_number TYPE HASHED TABLE OF t_phone_number WITH UNIQUE KEY name.
START-OF-SELECTION.
gt_phone_number = VALUE #(
( name = 'hans' number = '++498912345' )
( name = 'peter' number = '++492169837' )
( name = 'alice' number = '++6720915' )
).
* access
WRITE / gt_phone_number[ name = 'hans' ]-number.
* add
gt_phone_number = VALUE #( BASE gt_phone_number ( name = 'bernd' number = '++3912345' ) ).
* update
MODIFY TABLE gt_phone_number FROM VALUE #( name = 'bernd' number = '++123456' ).
IF line_exists( gt_phone_number[ name = 'alice' ] ).
WRITE / 'Yes, Alice is known.'.
ENDIF.
* all entries
LOOP AT gt_phone_number ASSIGNING FIELD-SYMBOL(<g_phone_number>).
WRITE: /, <g_phone_number>-name, <g_phone_number>-number.
ENDLOOP.
#Jagger's answer is great, but #guettli asked for shorter syntax. So just for completeness, there is of course always the possibility to wrap this in a class:
CLASS dictionary DEFINITION.
PUBLIC SECTION.
TYPES:
BEGIN OF row_type,
key TYPE string,
data TYPE string,
END OF row_type.
TYPES hashed_map_type TYPE HASHED TABLE OF row_type WITH UNIQUE KEY key.
METHODS put
IMPORTING
key TYPE string
data TYPE string.
METHODS get
IMPORTING
key TYPE string
RETURNING
VALUE(result) TYPE string.
METHODS get_all
RETURNING
VALUE(result) TYPE hashed_map_type.
METHODS contains
IMPORTING
key TYPE string
RETURNING
VALUE(result) TYPE abap_bool.
PRIVATE SECTION.
DATA map TYPE hashed_map_type.
ENDCLASS.
CLASS dictionary IMPLEMENTATION.
METHOD put.
READ TABLE map REFERENCE INTO DATA(row) WITH TABLE KEY key = key.
IF sy-subrc = 0.
row->*-data = data.
ELSE.
INSERT VALUE #( key = key
data = data )
INTO TABLE map.
ENDIF.
ENDMETHOD.
METHOD get.
result = map[ key = key ]-data.
ENDMETHOD.
METHOD get_all.
INSERT LINES OF map INTO TABLE result.
ENDMETHOD.
METHOD contains.
result = xsdbool( line_exists( map[ key = key ] ) ).
ENDMETHOD.
ENDCLASS.
Leading to:
DATA(phone_numbers) = NEW dictionary( ).
phone_numbers->put( key = 'hans' data = '++498912345' ).
phone_numbers->put( key = 'peter' data = '++492169837' ).
phone_numbers->put( key = 'alice' data = '++6720915' ).
" access
WRITE phone_numbers->get( 'hans' ).
" add
phone_numbers->put( key = 'bernd' data = '++3912345' ).
" update
phone_numbers->put( key = 'bernd' data = '++123456' ).
IF phone_numbers->contains( 'alice' ).
WRITE 'Yes, alice is known'.
ENDIF.
" all entries
LOOP AT phone_numbers->get_all( ) INTO DATA(row).
WRITE: / row-key, row-data.
ENDLOOP.
People rarely do this in ABAP because internal tables are so versatile and powerful. From my personal point of view, I'd like to see people build more custom data structures. Implementation details like HASHED or SORTED, see discussion in #Jagger's answer, are hidden away in a natural way when doing this.
Related
Is it good if we use lookup function in for each where clause? Will it cause performance issue? Please help to understand and provide the example how to avoid.
define variable cGroupID as character no-undo.
for each <table> no-lock where lookup(cGroupID,<table.fieldname>) <> 0:
**do something...**
end.
note - table field name can have multiple comma separated group
A lookup function cannot use an index, so yes you can introduce sub-par performance which can be avoided. See the following example using the sports database which will read all records when using lookup and will limit the set to what meets the criteria when breaking the parts out to individual query parts:
def var ii as int no-undo.
def var iread as int64 no-undo.
function reads returns int64:
find _file where _file._file-name = 'customer' no-lock.
find _tablestat where _tablestat._tablestat-id = _file._file-number no-lock.
return _tablestat._tablestat-read.
end function.
iread = reads().
for each customer
where lookup( customer.salesrep, 'dkp,sls' ) > 0
no-lock:
ii = ii + 1.
end.
message 'lookup - records:' ii 'read:' reads() - iread.
ii = 0.
iread = reads().
for each customer
where customer.salesrep = 'dkp'
or customer.salesrep = 'sls'
no-lock:
ii = ii + 1.
end.
message 'or - records:' ii 'read:' reads() - iread.
https://abldojo.services.progress.com/?shareId=6272e1223fb02369b2545bf4
Your example however seems to be performing a reverse lookup, ie the database field contains a comma separated list of values, which seems like not obeying the basic rules of database normalization.
If you want to keep the list in a single field, adding a word index on your comma separated field may help. You can then use contains.
I need to generate data using the below url via requests.get :
fields = ("")
response_2 = requests.get(BASEURL + 'services/v17.0/report-jobs/' + jobId + "?fields=" +fields ,
headers = header_param)
For the purpose of the question, both the BASEURL and the JobID are pre defined.
However, there are several field names in the dataset such as Date, [Agent Name], [Agent ID] etc. that I'm looking to generate.
When I leave the fields object blank, no data is generated.
When I try to define the fields object using
fields = ("Date, Agent Name")
or
fields = ("Date", "Agent Name")
I always get back the error : Invalid fields argument
What is the best way to fix this?
I'm not sure what result you want, but the problem is you're trying to concatenate a string and a tuple, and misusing a tuple.
requests.get(BASEURL + 'services/v17.0/report-jobs/' + jobId + "?fields=".join(str(i) for i in fields)
I'm querying a SQLite db file using the id column, which is UNIQUEIDENTIFIER type.
The two commands are :
SELECT * FROM scanned_images WHERE id = cast('5D878B98-71B2-4DEE-BA43-61D11C8EA497' as uniqueidentifier)
or
SELECT * FROM scanned_images WHERE id = '5D878B98-71B2-4DEE-BA43-61D11C8EA497'
However, the above commands both returned nothing.
I also tried:
SELECT * FROM scanned_images WHERE rowid = 1
this command returns the correct data.
There is no uniqueidentifier data type in SQLite.
According to the rules of type affinity described here in 3.1. Determination Of Column Affinity, the column's affinity is numeric.
All that this expression does:
cast('5D878B98-71B2-4DEE-BA43-61D11C8EA497' as uniqueidentifier)
is return 5.
You should have defined the column's data type as TEXT, because you have to treat it like TEXT and write the condition:
WHERE id = '5D878B98-71B2-4DEE-BA43-61D11C8EA497'
or:
WHERE id = '(5D878B98-71B2-4DEE-BA43-61D11C8EA497)'
if as shown in the image it contains surrounding parentheses.
I'm having some strange feeling abour sqlite3 parameters that I would like to expose to you.
This is my query and the fail message :
#query
'SELECT id FROM ? WHERE key = ? AND (userid = '0' OR userid = ?) ORDER BY userid DESC LIMIT 1;'
#error message, fails when calling sqlite3_prepare()
error: 'near "?": syntax error'
In my code it looks like:
// Query is a helper class, at creation it does an sqlite3_preprare()
Query q("SELECT id FROM ? WHERE key = ? AND (userid = 0 OR userid = ?) ORDER BY userid DESC LIMIT 1;");
// bind arguments
q.bindString(1, _db_name.c_str() ); // class member, the table name
q.bindString(2, key.c_str()); // function argument (std::string)
q.bindInt (3, currentID); // function argument (int)
q.execute();
I have the feeling that I can't use sqlite parameters for the table name, but I can't find the confirmation in the Sqlite3 C API.
Do you know what's wrong with my query?
Do I have to pre-process my SQL statement to include the table name before preparing the query?
Ooookay, should have looked more thoroughly on SO.
Answers:
- SQLite Parameters - Not allowing tablename as parameter
- Variable table name in sqlite
They are meant for Python, but I guess the same applies for C++.
tl;dr:
You can't pass the table name as a parameter.
If anyone have a link in the SQLite documentation where I have the confirmation of this, I'll gladly accept the answer.
I know this is super old already but since your query is just a string you can always append the table name like this in C++:
std::string queryString = "SELECT id FROM " + std::string(_db_name);
or in objective-C:
[#"SELECT id FROM " stringByAppendingString:_db_name];
In SQLite I can run the following query to get a list of columns in a table:
PRAGMA table_info(myTable)
This gives me the columns but no information about what the primary keys may be. Additionally, I can run the following two queries for finding indexes and foreign keys:
PRAGMA index_list(myTable)
PRAGMA foreign_key_list(myTable)
But I cannot seem to figure out how to view the primary keys. Does anyone know how I can go about doing this?
Note: I also know that I can do:
select * from sqlite_master where type = 'table' and name ='myTable';
And it will give the the create table statement which shows the primary keys. But I am looking for a way to do this without parsing the create statement.
The table_info DOES give you a column named pk (last one) indicating if it is a primary key (if so the index of it in the key) or not (zero).
To clarify, from the documentation:
The "pk" column in the result set is zero for columns that are not
part of the primary key, and is the index of the column in the primary
key for columns that are part of the primary key.
Hopefully this helps someone:
After some research and pain the command that worked for me to find the primary key column name was:
SELECT l.name FROM pragma_table_info("Table_Name") as l WHERE l.pk = 1;
For the ones trying to retrieve a pk name in android, and while using the ROOM library.
#Oogway101's answer was throwing an error: "no such column [your_table_name] ... etc.. etc...
my way of query submition was:
String pkSearch = "SELECT l.name FROM pragma_table_info(" + tableName + ") as l WHERE l.pk = 1;";
database.query(new SimpleSQLiteQuery(pkSearch)
I tried using the (") quotations and still error.
String pkSearch = "SELECT l.name FROM pragma_table_info(\"" + tableName + "\") as l WHERE l.pk = 1;";
So my solution was this:
String pragmaInfo = "PRAGMA table_info(" + tableName + ");";
Cursor c = database.query(new SimpleSQLiteQuery(pragmaInfo));
String id = null;
c.moveToFirst();
do {
if (c.getInt(5) == 1) {
id = c.getString(1);
}
} while (c.moveToNext() && id == null);
Log.println(Log.ASSERT, TAG, "AbstractDao: pk is: " + id);
The explanation is that:
A) PRAGMA table_info returns a cursor with various indices, the response is atleast of length 6... didnt check more...
B) index 1 has the column name.
C) index 5 has the "pk" value, either 0 if it is not a primary key, or 1 if its a pk.
You can define more than one pk so this will not bring an accurate result if your table has more than one (IMHO more than one is bad design and balloons the complexity of the database beyond human comprehension).
So how will this fit into the #Dao? (you may ask...)
When making the Dao "abstract" you have access to a default constructor which has the database in it:
from the docummentation:
An abstract #Dao class can optionally have a constructor that takes a Database as its only parameter.
this is the constructor that will grant you access to the query.
There is a catch though...
You may use the Dao during a database creation with the .addCallback() method:
instance = Room.databaseBuilder(context.getApplicationContext(),
AppDatabase2.class, "database")
.addCallback(
//You may use the Daos here.
)
.build();
If you run a query in the constructor of the Dao, the database will enter a feedback loop of infinite instantiation.
This means that the query MUST be used LAZILY (just at the moment the user needs something), and because the value will never change, it can be stored. and never re-queried.