Странное поведение в результате запроса Firebase SWIFT

Вам нужно быть немного осторожнее с вашими строковыми манипуляциями. Вы не можете использовать REPLACE() для этого, потому что это заменит несколько вхождений, развращая ваши данные, если один элемент в списке, разделенном запятыми, является подстрокой другого элемента. Функция INSERT() string лучше для этого, а не путать с оператором INSERT, используемым для вставки в таблицу.

DELIMITER $$

DROP PROCEDURE IF EXISTS `insert_csv` $$
CREATE PROCEDURE `insert_csv`(_list MEDIUMTEXT)
BEGIN

DECLARE _next TEXT DEFAULT NULL;
DECLARE _nextlen INT DEFAULT NULL;
DECLARE _value TEXT DEFAULT NULL;

iterator:
LOOP
  -- exit the loop if the list seems empty or was null;
  -- this extra caution is necessary to avoid an endless loop in the proc.
  IF LENGTH(TRIM(_list)) = 0 OR _list IS NULL THEN
    LEAVE iterator;
  END IF;

  -- capture the next value from the list
  SET _next = SUBSTRING_INDEX(_list,',',1);

  -- save the length of the captured value; we will need to remove this
  -- many characters + 1 from the beginning of the string 
  -- before the next iteration
  SET _nextlen = LENGTH(_next);

  -- trim the value of leading and trailing spaces, in case of sloppy CSV strings
  SET _value = TRIM(_next);

  -- insert the extracted value into the target table
  INSERT INTO t1 (c1) VALUES (_next);

  -- rewrite the original string using the `INSERT()` string function,
  -- args are original string, start position, how many characters to remove, 
  -- and what to "insert" in their place (in this case, we "insert"
  -- an empty string, which removes _nextlen + 1 characters)
  SET _list = INSERT(_list,1,_nextlen + 1,'');
END LOOP;

END $$

DELIMITER ;

Далее, таблица для test:

CREATE TABLE `t1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `c1` varchar(64) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Новая таблица пуста.

mysql> SELECT * FROM t1;
Empty set (0.00 sec)

Вызовите процедуру.

mysql> CALL insert_csv('foo,bar,buzz,fizz');
Query OK, 1 row affected (0.00 sec)

Обратите внимание, что «1 строка затронута» не означает, что вы ожидаете. Это относится к последней вставке, которую мы сделали. Поскольку мы вставляем по одной строке за раз, если процедура вставляет не менее в одну строку, вы всегда получите количество строк в 1; если процедура ничего не вставляет, вы получите 0 строк.

Это сработало?

mysql> SELECT * FROM t1;
+----+------+
| id | c1   |
+----+------+
|  1 | foo  |
|  2 | bar  |
|  3 | buzz |
|  4 | fizz |
+----+------+
4 rows in set (0.00 sec)

0
задан vincenzo 16 January 2019 в 14:17
поделиться

1 ответ

Я обнаружил, что проблема в том, как я приводил результаты запроса. Приведение его к типу [String: String] приводит к возвращению, потому что на самом деле результат был [String [String: String]], когда все значения для параметра записи были String, но так как я изменил Время открытия и Время закрытия на Int, чем я должен читать снимок как [String [String: Any]]. Итак, последняя функция:

func filterOpenShops(setCompletion: @escaping (Bool) -> ()) {
        // Empty the array for beginning of the search
        self.availableShopsArray.removeAll()
        var ref = Database.database().reference()

        ref.child("Continent").child("Europe").child("Country").child("Italy").child("Region").child("Emilia-Romagna").child("City").child("Bologna").child("Shops").child("Shops Opening Times").queryOrdered(byChild: "Opening Time").queryStarting(atValue: openingTimeQueryStart).queryEnding(atValue: openingTimeQueryEnd).observe(.value) { (snapshot) in
            print(snapshot)
            if let data = snapshot.value as? [String : [String : Any]] {
                for (_, value) in
                    data {
                        let shopName = value["Shop Name"] as! String
                        let active = value["Active"] as! String
                        if active == "true" {
                            self.availableShopsArray.append(shopName)
                            print("Shop_Name is :\(shopName)")
                            print("self.availableShopsArray is: \(self.availableShopsArray)")
                        }
                }

            } else {
                print("No Shops")
            }
            // still asynchronous part
            setCompletion(true)
            // call next cascade function filterClosedShops only when data retrieving is finished
            self.filterClosedShops(setCompletion: self.completionSetter)

            print("  1 Open Shops are \(self.availableShopsArray)")
        }
    } // end of filterOpenShops()
0
ответ дан vincenzo 16 January 2019 в 14:17
поделиться
Другие вопросы по тегам:

Похожие вопросы: