Creating multiple tables with single query statement using swift - ios
I am trying to create two tables with a single query statement. However, below code is creating just 'myprofile' table only. It doesn't create 'groups' table. Am I missing something here? Can someone please help.
let createTableString = """
CREATE TABLE `myprofile` (`profile_id` VARCHAR , `first_name` VARCHAR , `profile_type` VARCHAR ,`preferences` VARCHAR);
CREATE TABLE `groups` (`account_id` VARCHAR ,`unique_url` VARCHAR, `title` VARCHAR, `participant_id` VARCHAR ,`create_date` VARCHAR,`synced` VARCHAR);
"""
private func createTable() {
var createTableStatement: OpaquePointer?
if sqlite3_prepare_v2(db, createTableString, -1, &createTableStatement, nil) == SQLITE_OK {
if sqlite3_step(createTableStatement) == SQLITE_DONE {
print("\table's are created.")
} else {
print("\table's are not created.")
}
} else {
print("\nCREATE TABLE statement is not prepared.")
}
sqlite3_finalize(createTableStatement)
}
Related
Snowflake Stored Procedure Not Inserting Record Though No Error
Can someone tell me why this would run but not actually insert a record? When I return the actual query as a variable the code works perfectly in Snowflake: CREATE OR REPLACE PROCEDURE Z_PC_FIVETRAN_DB.BLOB_RAW_CATALOGS.SP_FULL_AND_IS_HERRING_MOVE_CURRENT_DELETED_TO_PCFIVE(ACTION_TYPE VARCHAR,UPLOAD_ID VARCHAR,VENDOR VARCHAR) RETURNS VARCHAR LANGUAGE JAVASCRIPT AS $$ var sql_textA = "INSERT INTO Z_PC_FIVETRAN_DB.BLOB_RAW_CATALOGS.RAW_CATALOGS (M_PDT_CODE) SELECT M_PDT_CODE FROM Z_CATALOGS_NEW.PUBLIC.CATALOGS_RAW WHERE M_VENDOR_NAME='HERRING' AND M_PDT_CODE NOT IN (SELECT M_PDT_CODE FROM Z_PC_FIVETRAN_DB.BLOB_RAW_CATALOGS.RAW_CATALOGS WHERE M_UPLOAD_ID='" +UPLOAD_ID+ "' AND M_PDT_CODE IS NOT NULL)" var sql_commandA = snowflake.createStatement({ sqlText: sql_textA}) if (VENDOR=='HERRING' && ACTION_TYPE=='FULL') { var db = sql_commandA.execute() return sql_textA } else { return 'Not HERRING Or Not FULL' } $$;
I ran your code and am able to insert rows. Only thing I can think of is if AUTOCOMMIT is turned off for you and if you need to explicitly call COMMIT. Try to call COMMIT after the INSERT and see if it works. ALTER SESSION SET AUTOCOMMIT = FALSE; CREATE OR REPLACE TABLE CATALOGS_RAW(M_VENDOR_NAME VARCHAR, M_PDT_CODE VARCHAR); CREATE TABLE RAW_CATALOGS(M_PDT_CODE VARCHAR,M_UPLOAD_ID VARCHAR); INSERT INTO CATALOGS_RAW VALUES('HERRING','PDT0002'); INSERT INTO CATALOGS_RAW VALUES('HERRING','PDT0003'); INSERT INTO CATALOGS_RAW VALUES('HERRING','PDT0005'); COMMIT; SELECT * FROM CATALOGS_RAW; INSERT INTO RAW_CATALOGS VALUES('PDT0001','UPD0001'); SELECT * FROM RAW_CATALOGS; CREATE OR REPLACE PROCEDURE TESTPROC(ACTION_TYPE VARCHAR,UPLOAD_ID VARCHAR,VENDOR VARCHAR) RETURNS VARCHAR LANGUAGE JAVASCRIPT AS $$ var sql_textA = "INSERT INTO RAW_CATALOGS (M_PDT_CODE) SELECT M_PDT_CODE FROM CATALOGS_RAW WHERE M_VENDOR_NAME='HERRING' AND M_PDT_CODE NOT IN (SELECT M_PDT_CODE FROM RAW_CATALOGS WHERE M_UPLOAD_ID='" +UPLOAD_ID+ "' AND M_PDT_CODE IS NOT NULL)" var sql_commandA = snowflake.createStatement({ sqlText: sql_textA}) if (VENDOR=='HERRING' && ACTION_TYPE=='FULL') { var db = sql_commandA.execute() return sql_textA } else { return 'Not HERRING Or Not FULL' } $$; CALL TESTPROC('FULL','UPD0003','HERRING'); COMMIT;
Update/insert table with wrong column name - iOS
I have a table with 5 columns and sometimes I update or insert new entries inside that table. I get the key/values from a json service, but this service added one more field and now when I try to update or insert new entries inside the table I get the error: Values not inserted. Error: no such column: email I get that error from this line: sqlite3_prepare(_database, queryChar, -1, &statement, NULL); if (sqlite3_step(statement) != SQLITE_DONE) NSLog(#"Values not inserted. Error: %s",sqlite3_errmsg(_database)); queryChar has this format: UPDATE contents SET [id] = ?,[phone] = ?,[name] = ?,[websiteurl] = ?,[postalcode] = ?,[email] = ?,[url] = ? WHERE id = 69 I wonder which is the most effective approach to solve this kind of error. Should I check every column name if it exist in the table and then add it to the queryChar ?
For creating your table you need to create it like CREATE TABLE IF NOT EXISTS MYTABLENAME(ID INTEGER PRIMARY KEY AUTOINCREMENT,id TEXT,TABLECOLUMN1 TEXT, TABLECOLUMN2 TEXT, TABLECOLUMN3 TEXT); Also you have to change your database for adding new column in your database [its mandatory to alter your table to add new column added later in your existing table] -(void)ChangeDB:(NSInteger)newDbVersion { switch (newDbVersion) { case 1: { "ALTER TABLE MYTABLENAME ADD COLUMN NEWCOLUMNTOBEADD TEXT" //run this query in your sqlite } break; default: break; } } Here is your update query now after fetch data from json where NEWCOLUMNTOBEADD is new data added in your database table at runtime update MYTABLENAME set TABLECOLUMN1 ='%#', TABLECOLUMN2='%#', TABLECOLUMN3='%#', NEWCOLUMNTOBEADD = '%#' where id ='%#' More about ALTER command
how to insert new row by using executeUpdate - FMdatabase
I'm using fmdb library. https://github.com/ccgus/fmdb I would like to insert new records but I don't know how can I do: if let db = database, let q = db.executeUpdate("insert into \(table) (catid,subcat_id,id,subcat_title,title,description,lat,lon,takhfif,images,wifi,apple_health,wc,full_time,pos,work_hours,phone,mobile,fax,website,email,address,facebook,instagram,linkedin,telegram,googleplus,twitter,publish,feature,manager,city,rating_sum,rate_count,lastip,parking,isMallID,mallID,discount_images,price_images,newProduct_images,services_images,order_online,out_upon,cat_title,cat_icon,last_modify,item_logo,cat_logo,rate_sum1,rate_sum2,rate_sum3,rate_count1,rate_count2,rate_count3,rate_title1,rate_title2,rate_title3,rate_enable) values (\(catid),\(subcat_id),\(id),'\(subcat_title)','\(title)','\(description)','\(lat)','\(lon)','\(takhfif)','\(images)',\(wifi),\(apple_health),\(wc),\(full_time),\(pos),'\(work_hours)','\(phone)','\(mobile)','\(fax)','\(website)','\(email)','\(address)','\(facebook)','\(instagram)','\(linkedin)','\(telegram)','\(googleplus)','\(twitter)',\(publish),\(feature),'\(manager)','\(city)',\(rating_sum),\(rate_count),'\(lastip)',\(parking),\(isMallID),\(mallID),'\(discount_images)','\(price_images)','\(newProduct_images)','\(services_images)',\(order_online),\(out_upon),'\(cat_title)','\(cat_icon)',\(last_modify),'\(item_logo)','\(cat_logo)',\(rate_sum1),\(rate_sum2),\(rate_sum3),\(rate_count1),\(rate_count2),\(rate_count3),'\(rate_title1)','\(rate_title2)','\(rate_title3)',\(rate_enable))") { } but I got this message before building: cannot invoke executeUpdate with an argument list of type string
You used the api wrong. The first parameter is the sql, each value has to be represented with an "?". The second one (values) is an array of the values. Try this: if let db = database, let q = db.executeUpdate( "insert into \(table) (catid,subcat_id,id,subcat_title,title,description,lat,lon,takhfif,images,wifi,apple_health,wc,full_time,pos,work_hours,phone,mobile,fax,website,email,address,facebook,instagram,linkedin,telegram,googleplus,twitter,publish,feature,manager,city,rating_sum,rate_count,lastip,parking,isMallID,mallID,discount_images,price_images,newProduct_images,services_images,order_online,out_upon,cat_title,cat_icon,last_modify,item_logo,cat_logo,rate_sum1,rate_sum2,rate_sum3,rate_count1,rate_count2,rate_count3,rate_title1,rate_title2,rate_title3,rate_enable) values (?, ?, ? ...., ?, ?, ? )" values: [catid, subcat_id, id, subcat_title, title, description, lat, lon, takhfif, images, wifi, apple_health, wc, full_time, pos, work_hours, phone, mobile, fax, website, email, address, facebook, instagram, linkedin, telegram, googleplus, twitter, publish, feature, manager, city, rating_sum, rate_count, lastip, parking, isMallID, mallID, discount_images, price_images, newProduct_images, services_images, order_online, out_upon, cat_title, cat_icon, last_modify, item_logo, cat_logo, rate_sum1, rate_sum2, rate_sum3, rate_count1, rate_count2, rate_count3, rate_title1, rate_title2, rate_title3, rate_enable]) { } Note: I didn't count the values, so you have to ensure that the count of "?" inside of the string is exactly the count of your values! Maybe you should think about a function to improve the readability of your code. Something like that: extension FMDatabase { func insert(into table: String, row values: [(column: String, content: Any)]) { guard (values.count > 0) else { fatalError(values.count > 0, "Inserting nothing into a table makes no sense!") } var sql = "INSERT INTO \(table) (" var contents: [Any] = [] for (index, value) in values.enumerated() { sql += index == 0 ? value.column : ", \(value.column)" contents.append(value.content) } sql += ") VALUES (" for index in 0..<values.count { sql += index == 0 ? "?" : ", ?" } sql += ")" executeUpdate(sql, values: contents) } } Then you can insert values like that: if let db = database { db.insert( into: table, row: [ (column: "catid", content: catid), (column: "subcat_id", content: subcat_id), ... (column: "rate_enable", content: rate_enable) ] ) } Isn't it better readable?
Error loading association from controller in cakephp
I can't get this simple query right. I need to join my adresses table to my annonces table. I supose this should be farly strait forward but I simply can't get it to work. I firstly made my adresse table object like this class AdressesTable extends Table { public function initialize(array $config) { $this->belongsTo('Annonces', [ 'foreignKey' => 'annonceId', 'joinType' => 'INNER', ]); } } Then in my annonces controller I tryed to join the adresses like this public function view($id = null) { if (!$id) { throw new NotFoundException(__('Annonce invalide!')); } $query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['id' => $id]); $annonce = $query->firstOrFail(); $this->set(compact('annonce')); } But then I got this error : Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Adresses.annonce_id' in 'where clause' Witch I don't understand why I got it since I have defined my foreign key in the AdressesTable class. The query I would like to have at the end would look like this SELECT * FROM annonces INNER JOIN adresses ON adresses.annonceId = annonces.id WHERE annonces.id = #param *PS. I know it wont be select * but rather select [all my column]* EDIT : My table schema are as following CREATE TABLE annonces( id INT NOT NULL AUTO_INCREMENT, #PK startDate DATE NOT NULL, endDate DATE NOT NULL, title VARCHAR(128) NOT NULL, descript TEXT NOT NULL, infoSupplementaire TEXT NULL, premium BIT NOT NULL, clientId INT NOT NULL, #FK categorieId INT NOT NULL, #FK CONSTRAINT pk_annonces_id PRIMARY KEY (id), CONSTRAINT fk_annonces_clientId FOREIGN KEY (clientId) REFERENCES clients(id), CONSTRAINT fk_annonces_categorieId FOREIGN KEY (categorieId) REFERENCES categories(id) ); CREATE TABLE adresses( id INT NOT NULL AUTO_INCREMENT, #PK latitude DECIMAL(11,7), longitude DECIMAL(11,7), adresse VARCHAR(512), annonceId INT NOT NULL, #FK CONSTRAINT pk_adresses_id PRIMARY KEY (id), CONSTRAINT fk_adresses_annonceId FOREIGN KEY (annonceId) REFERENCES annonces(id) ) I solved my problem by renaming my column folowing cakephp convention and using any of the code from this answer
You can try $query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['Annonces.id' => $id]); $annonce = $query->firstOrFail(); OR public function view($id = null) { if (!$id) { throw new NotFoundException(__('Annonce invalide!')); } $annonceEntity = $this->Annonces->get($id); $query = $this->Annonces->find('all', ['contain' => ['Adresses']])->where(['Annonces.id' => $annonceEntity->id]); $annonce = $query->firstOrFail(); $this->set(compact('annonce')); }
Disable automatic index on related object id from yml
Doctrine Automatically creates indexes on columns that are used to define object relations, For example user: id, name message: id, sender_id, receiver_id, message if I define relationship between message and user in a way that message has one Sender and has one Receiver, doctrine will automatically index sender_id and receiver_id fields when I generate sql from model. I would like to disable index on sender, because I manually create index with sender_id and receiver id together. How can I disable auto generated index?
Hello I assumed you were using MySQL, and took a look in Doctrine/Export/Mysql.php I found this : // build indexes for all foreign key fields (needed in MySQL!!) if (isset($options['foreignKeys'])) { foreach ($options['foreignKeys'] as $fk) { $local = $fk['local']; $found = false; if (isset($options['indexes'])) { foreach ($options['indexes'] as $definition) { if (is_string($definition['fields'])) { // Check if index already exists on the column $found = $found || ($local == $definition['fields']); } else if (in_array($local, $definition['fields']) && count($definition['fields']) === 1) { // Index already exists on the column $found = true; } } } if (isset($options['primary']) && !empty($options['primary']) && in_array($local, $options['primary'])) { // field is part of the PK and therefore already indexed $found = true; } if ( ! $found) { if (is_array($local)) { foreach($local as $localidx) { $options['indexes'][$localidx] = array('fields' => array($localidx => array())); } } else { $options['indexes'][$local] = array('fields' => array($local => array())); } } } } If I understand correctly, to disable the index should be part of the primary key.