How do I perform a transaction in dart mysql1.
I tried doing this,
await pool.transactional((conn) async {});
But the key wait pool is showing this error
Undefined name 'pool'.
Try correcting the name to one that is defined, or defining the name.dartundefined_identifier
try this instead
await MySqlConnection.connect(MYSQL_SETTING).transaction((context) async {})
Related
I am testing a website and I have this error message that shows up every once in a while when I'm executing the automation for the tests due to the websites load issues. The error message shows up only some of the times in random locations during the test. Sometimes it shows after I click on button x. The next time it'll happen when I click on button y. So it is hard to predict exactly when the error message will show. I do not want to have to write an assertion after every single action in my script (such as having the same assertion after every page.locator.click()) How can I do something like "If an error message with locator x shows up at any point during this entire test, fail the test and display this message"? The assertion I am currently using is await expect(locator,"Error Message").not.tobeVisible(), which is using a locator only visible in the error message. So the words "Error Message" is displayed and the test is failed, indicating that the failed test was a result of the error message. (The error message is occurring due to db load issues).
I can do an assertion such as
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible()
await page.locator.click();
await page.locator.click();
await page.locator.click();
but the assertion here only applies to checking for the error message after the first click. Sometimes it occurs after the 2nd click, 3rd click, etc. It's an error message from the website indicating load issues. So the test will fail eventually but I'd like to have the assertion of await expect(locator,"Error Message").not.tobeVisible() apply throughout the test and not have to do something like putting the assertion after every single action like this:
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await page.locator.click();
await expect(locator,"Error Message").not.tobeVisible();
await expect(locator,"Error Message").not.tobeVisible() only checks for a particular instance when explicitly stated, and not constantly checking throughout the entire test.
It would be great to do be able to write an assertion of await expect(locator,"Error Message").not.tobeVisible() once so that it applies throughout the entire test, and not having to write it multiple times after each click/action due to the error messages unpredictable nature.
You can create one liner error message verifier and call in places where you know its most likely to occur:
async ValidateNoError() {
expect(await this.page.locator(Errorbannermessage).count()).toEqual(0);
}
This way you can easily delete/update/comment later as required.
I have a confusion in understanding Dart's async/await functionality. Most tutorials use the following example:
Future<String> createOrderMessage() async {
var order = await fetchUserOrder();
return 'Your order is: $order';
}
Future<String> fetchUserOrder() =>
// Imagine that this function is
// more complex and slow.
Future.delayed(
const Duration(seconds: 2),
() => 'Large Latte',
);
Future<void> main() async {
print('Fetching user order...');
print(await createOrderMessage());
}
I understand that the fetchUserOrder function returns a Future. Anyone who calls this function will immediately get a Future object as a result but this Future object may not have the real result value at that time. It will be filled up in "future".
Now, the createOrderMessage function calls: await fetchUserOrder(); This means, the control will wait till fetchUserOrder() returns a completed/non-empty Future. Am I right here? Is this what await does?
If that is correct, it means, the createOrderMessage function is essentially synchronous now because it won't return until the Future returned by fetchUserOrder is filled. Thus, the order variable in this function is initialized with a completed Future. Then why does this function need the "async" keyword in its function declaration? What does it signify?
Second confusion is if Dart is single threaded, when and how exactly is an async function executed? If I invoke multiple method calls that return Futures like this without await:
...
Future<A> fa = getA();
Future<B> fb = getB();
Future<C> fa = getC();
...
Will the functions getA, getB, and getC be executed sequentially in the background or they will be executed "in parallel" somehow?
Now, the createOrderMessage function calls: await fetchUserOrder(); This means, the control will wait till fetchUserOrder() returns a completed/non-empty Future. Am I right here? Is this what await does?
Yes. the await keyword means you get the completed T instead of Future<T> in return. So:
var a = fetchUserOrder(); // Type of a: Future<String>
var b = await fetchUserOrder(); // Type of b: String
When you use await, you tell the code to await the completion of the process and get the actual result. But without await, the stream is in the future and is in process until you await it somewhere else.
why does this function need the "async" keyword in its function declaration?
It's a rule to specify long-running functions. So when a function awaits for a long running process to complete, the function itself is also a long-running process. Why? Because it's waiting for another one to complete.
Therefore, you need to specify async for that as well. When another function is calling this one, it also knows this one might be long-running.
In short, every awaitable function needs to be in an async function.
Second confusion is if Dart is single threaded, when and how exactly is an async function executed?
You're mixing the concept of parallelism with asynchronous. An async process does not have to be done in multi thread.
Async processes can be one one at time, but in a different order in compare to synchronous code.
Take a look at this article which explains asynchronous in a single thread.
Now, the createOrderMessage function calls: await fetchUserOrder(); This means, the control will wait till fetchUserOrder() returns a completed/non-empty Future. Am I right here? Is this what await does?
If that is correct, it means, the createOrderMessage function is essentially synchronous now because it won't return until the Future returned by fetchUserOrder is filled. Thus, the order variable in this function is initialized with a completed Future.
await allows asynchronous functions to have the appearance of synchronous functions by allowing asynchronous code to be structured very similarly to synchronous code. In your example, it's syntactic sugar for registering a Future.then() callback and immediately returning:
Future<String> createOrderMessage() {
var future = fetchUserOrder().then((order) {
return 'Your order is: $order';
});
return future;
}
await defers execution of the rest of that function; it does not wait and block execution of your entire thread. Your program will continue running its event loop, possibly allowing other asynchronous operations to make progress.
Will the functions getA, getB, and getC be executed sequentially in the background or they will be executed "in parallel" somehow?
As I mentioned in comments, it depends on how getA, getB, and getC are implemented. They could run in parallel, such as if they run in separate Dart isolates or in separate threads in the Dart VM/runtime.
I'm converting dart code to nnbd.
I have the following code.
var subscription = response.listen(
(newBytes) async {
/// if we don't pause we get overlapping calls from listen
/// which causes the [writeFrom] to fail as you can't
/// do overlapping io.
subscription.pause();
/// we have new data to save.
await raf.writeFrom(newBytes);
subscription.resume();
});
The problem is I get the following error:
The non-nullable local variable 'subscription' must be assigned before it can be used.
Try giving it an initializer expression, or ensure that it's assigned on every execution path.
I've had a similar problem solved here:
dart - correct coding pattern for subscription when using null saftey?
which was answered by #lrn
However the pattern solution pattern doesn't seem to work in this case.
raf.writeFrom is an async operation so I must use an 'async' method which means I can't use the 'forEach' solution as again I don't have access to the subscription object.
If you really want to use listen, I'd do it as:
var subscription = response.listen(null);
subscription.onData((newBytes) async {
subscription.pause();
await raf.writeFrom(newBytes);
subscription.resume();
});
or, without the async:
var subscription = response.listen(null);
subscription.onData((newBytes) {
subscription.pause(raf.writeFrom(newBytes));
});
which will pause the subscription until the future returned by raf.writeFrom completes (it shouldn't complete with an error, though).
If using listen is not a priority, I'd prefer to use an asynchronous for-in like:
await for (var newBytes in subscription) {
await raf.writeFrom(newBytes);
}
which automatically pauses the implicit subscription at the await and resumes it when you get back to the loop.
Both with stream.listen and the StreamController constructor, null safety has made it nicer to create them first without callbacks, and then add the callbacks later, if the callback needs to refer to the subscription/controller.
(That's basically the same nswer as in the linked question, only applied to onData instead of onDone. You have to pass a default onData argument to listen, but it can be null precisely to support this approach.)
I don't think your code, as written, was legal before null-safety either; you can't reference a variable (subscription) before it's declared, and the declaration isn't complete until after the expression you initialize it with (response.listen(...)) is evaluated. You will need to separate the declaration from the initialization to break the circular dependency:
StreamSubscription<List<int>> subscription;
subscription = response.listen(...);
I wrote next code that run generation and insert SQL in DB db by incoming JSON.
Future<dbEnums> matchAndInsert(String section, Map jsonMap) async {
tableToInsert = "notifications";
try {
db.saveOriginalJson(jsonMap);
await db.KVToTableInsert(tableToInsert, jsonMap);
KVToTableInsert inside store some temp data (like names of nested tables that I am extracting from JSON).
The request handler is done in next way:
app.post('/foo', (req, res) async {
dbEnums insertResult = await matchQuery.foo("tablename", req.body);
This code work fine if I am sending data to handler from one thread (desktop C# app that can work in n threads). But it crush if I am trying to do it with few threads of parser (different root and nested tables). In error I am seeing that it's try to insert data to table2 while some fields are from table1.
Do I an using async wrong? Because it's look like data in method is overlapping?
How to fix code?
Am I right understand that I am overwriting field in saveOriginalJson before KVToTableInsert is complete? How to fix it?
db.saveOriginalJson(jsonMap);
await db.KVToTableInsert(tableToInsert, jsonMap);
P.S. more code if it needed https://gist.github.com/bubnenkoff/517e485757955a52494280977a85fb66
Being new to Dart/Flutter I am using this snippet to try and load a config.json file that I have stored in my assets folder. In trying to read this file, I am using models on the Dart language Futures documentation and in the Flutter docs on reading local text files:
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;
import 'dart:convert';
Future<List> loadAsset() async {
String raw = await rootBundle.loadString('assets/config.json');
List configData = json.decode(raw);
return configData;
}
Then, inside my class, I try to load the config into a List, like this:
Future<List> configData = loadAsset();
print(configData.toString());
// prints out: Instance of 'Future<List<dynamic>>'
The result of all this seems to work. Yet I can find no way of using the data I have loaded. Any effort to access elements in the List, e.g. configData[0] results in an error:
The following _CompileTimeError was thrown building
HomePage(dirty, state: HomePageState#b1af8):
'package:myapp/pages/home_page.dart': error:
line 64 pos 19: lib/pages/home_page.dart:64:19:
Error: The method '[]' isn't defined for the class
'dart.async::Future<dart.core::List<dynamic>>'.
Try correcting the name to the name of an existing method,
or defining a method named '[]'.
I would like to convert the configData Future into a normal object that I can read and pass around my app. I am able to do something very similar, and to get it to work inside a widget's build method, using a FutureBuilder and the DefaultAssetBundle thus...
DefaultAssetBundle
.of(context)
.loadString('assets/config.json')
...but I don't want the overhead of reloading the data inside all the widgets that need it. I would like to load inside a separate Dart package and have it available as a global configuration across all my app. Any pointers would be appreciated.
I have tried the suggestion by Rémi Rousselet:
List configData = await loadAsset();
print(configData[0]);
In this case, I get a compiler error:
compiler message: lib/pages/home_page.dart:55:21: Error: Getter not found: 'await'.
compiler message: List configData = await loadAsset();
compiler message: ^^^^^
You can't do configData[0] as configData is not a List but a Future.
Instead, await the future to have access to the List inside
List configData = await loadAsset();
print(configData[0]);
You can only use await INSIDE async methods.
If you want to you your assets in entire application you want to load the asset in the main method similar like this.
void main() async {
StorageUtils.localStorage = await SharedPreferences.getInstance();
}
Now you can use localStorage synchronously in entire application and you don't need to deal with another asynchronous calls or load it again.
Different example, same principle.