After running this code, the data will be inserted into the database. when I check the database, I find a row added with values: int_field=0 and other="" (empty string)
My question is how to throw exception in case of Null/empty insert.
from datetime import datetime
db = pw.MySQLDatabase('tests', user = 'root', password = 'root', host = 'localhost', port = 3306)
class Model(pw.Model):
name = pw.CharField()
created_at = pw.DateTimeField(default = datetime.now())
other = pw.CharField(null = False)
int_field = pw.IntegerField(null = False)
class Meta:
database = db
db_table = 'nmodel'
Model.create_table()
Model.create(name = "tests")
Its a MySQL strict_mode issue, you should enable it in peewee Database Instance Like below.
Add this (sql_mode='STRICT_ALL_TABLES') to the constrcutor call:
db=pw.MySQLDatabase('database_name', user='user_name', password='user_psswd',
host='host_name', port=port_num,sql_mode='STRICT_ALL_TABLES')
This will throw a mysql exception when null values are passed.
I think you need to set your sql_mode to be more strict. See:
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sql-mode-setting
Specifically, I think you're running into:
https://dev.mysql.com/doc/refman/8.0/en/sql-mode.html#sqlmode_no_auto_value_on_zero
Related
I have a model:
class Tasks(models.Model):
name = models.CharField(max_length = 50, null = True, blank = True)
assigned_to = models.ManyToManyField(User, null = True, blank = True)
I have to execute a query
tasks_for_myuser = Tasks.objects.filter(assigend_to__contains = myuser)
But this is throwing an error.
django.core.exceptions.FieldError: Related Field got invalid lookup: contains
Please help!
If you are trying to filter Tasks which has assigned_to field set to myuser, you can simply query like this.
tasks_for_myuser = Tasks.objects.filter(assigend_to = myuser)
You don't really require contains here, since it is a many-to-many field.
I have 2 models on my search function joined by a field an I want to create an ActiveDataProvider for my GridView. This is what I have so far:
My yii db config:
db => users logs data;
db1 => system data;
Model1 and Model2 are in db1
public function search($params)
{
// (...)
$query1 = Model1::find();
$query2 = Model2::find();
$query1->select(
new Expression ("'Data model1: ' Model"),
'model1.id',
'model1.columns',
)->jointWith(['mODEL2'])
->andWhere(new Expression ('model1.id || model1.columns != model2.id || model2.columns'));
$query2->select(
new Expression ("'Data model2: ' Model"),
'model2.id',
'model2.columns',
)->jointWith(['mODEL1'])
->andWhere(new Expression ('model1.id || model1.columns != model2.id || model2.columns'));
$unionQuery = (new Query())->from(['dummy_name'=>$query1->union($query2)]);
$dataProvider = new ActiveDataProvider([
'query'=>$unionQuery,
]);
// (...)
return $dataProvider;
}
And the server database exception:
the table or view not exist
In my models (1 and 2) I do specific that I use the db1 connection, but how can I do that in the $unionQuery without use $unionQuery->all(Yii::$app->db1)?
That do not work.
How can i do that in the $unionQuery without use $unionQuery->all(Yii::$app->db1)???
You cannot. DB connection should be specified on query execution.
In your case query is executed at ActiveDataProvider level so you should set ActiveDataProvider::$db property with correct db connection.
In your case query is executed at ActiveDataProvider level so you
should set ActiveDataProvider::$db property with correct db
connection.
awesome thanks a lot this works
$dataProvider = new ActiveDataProvider([
'query'=>$unionQuery,
'db'=>Yii::$app->db1,
]);
I am using Akka.Net (v 1.3.2) and am trying to query the event journal for all events with a specific tag. I only want the events that exist at the time I query the journal. Inside an actor, I have the following code:
var readJournal = PersistenceQuery.Get(Context.System).ReadJournalFor<SqlReadJournal>(SqlReadJournal.Identifier);
var stream = readJournal.CurrentEventsByTag("The Tag Name", Offset.NoOffset());
var materializer = ActorMaterializer.Create(Context.System);
stream.RunForeach(envelope =>
{
// Do some stuff with the EventEnvelope
}, materializer).Wait();
This will successfully query the event journal. However, the problem is it will only return the first 100 events. I need all of them that match the query!
Question: How do I remove the limit/filter that exists when querying the event journal by tag name?
If you need it, here is my akka.persistence configuration:
var config = Akka.Configuration.ConfigurationFactory.ParseString(#"
akka.persistence {
journal {
plugin = ""akka.persistence.journal.sql-server""
sql-server {
class = ""Akka.Persistence.SqlServer.Journal.SqlServerJournal, Akka.Persistence.SqlServer""
connection-string = """ + connectionString + #"""
schema-name = dbo
table-name = __akka_EventJournal
metadata-table-name = __akka_Metadata
auto-initialize = on
}
}
snapshot-store {
plugin = ""akka.persistence.snapshot-store.sql-server""
sql-server {
class = ""Akka.Persistence.SqlServer.Snapshot.SqlServerSnapshotStore, Akka.Persistence.SqlServer""
connection-string = """ + connectionString + #"""
schema-name = dbo
table-name = __akka_SnapshotStore
auto-initialize = on
}
}
}"
);
There are two things to check out:
You can set the maximum number of messages returned in one query by setting up akka.persistence.query.journal.sql.max-buffer-size value (see: reference.conf).
Use readJournal.EventsByTag instead of readJournal.CurrentEventsByTag to get a continuous stream of events. Just keep in mind, that it won't complete by itself, but will live on waiting for new events to arrive. You can stop it explicitly i.e. by using KillSwitch.
In application.conf, parameters are set:
url = "jdbc:mysql://.../table_name"
user = ...
password = ...
driver = "com.mysql.jdbc.Driver"
connectionPool = HikariCP
queueSize = 25000
I am still receiving an error whenever the queue reaches 1000 items, meaning that the queueSize property is still the default value.
Task scala.slick.backend.DatabaseComponent$DatabaseDef$...
rejected from java.util.concurrent.ThreadPoolExecutor...
[Running, pool size = 20,
active threads = 20,
queued tasks = 1000,
completed tasks = 7507]
Not sure why it's not picking up your value, but you might want to try a different way of configuring.. you didn't say what version of Slick you are using. But please refer to the Slick 3.0.0 documentation. Try it using TypeSafe Config:
In your application.conf:
database {
dataSourceClass = "org.postgresql.ds.PGSimpleDataSource" // replace with mysql driver
properties = {
databaseName = "mydb"
user = "myuser"
password = "secret"
}
queueSize = 25000 // I've never changed that property, so not tested.
}
Then in scala:
val db = Database.forConfig("database")
Hope this works for you.
I been trying to get sqlcachedependecy working, but it doesn't appear to work
I got the proper settings in my web.config and also global.asa, however when I run this query and the changes are made to the database from either with in or outside the web site the cached objects are not updated please someone help? I know its not because this query is querying a view, because I tested this using straight SqlDependecy and the notification works fine.
public IQueryable<VictoryList> GetVictoryList()
{
string cacheKey = HttpContext.Current.User.Identity.Name + "victoryCacheKey";
IQueryable<VictoryList> cachednews = (IQueryable<VictoryList>)HttpContext.Current.Cache.Get(cacheKey);
if (cachednews == null)
{
var results = from v in _datacontext.ViewVictoryLists
orderby _datacontext.GetNewId()
select new VictoryList
{
MemberID = v.MemberID,
Username = v.Aspnetusername,
Location = v.Location,
DaimokuGoal = v.DaimokuGoal,
PreviewImageID = v.PreviewImageID,
TotalDaimoku = v.TotalDaimoku,
TotalDeterminations = v.TotalDeterminations,
DeterminationID = v.DeterminationID,
DeterminationName = v.DeterminationName
};
results = results.ToList().AsQueryable();
SqlCacheDependencyAdmin.EnableNotifications(_datacontext.Connection.ConnectionString);
SqlCacheDependency dependency =
new SqlCacheDependency(_datacontext.GetCommand(results) as SqlCommand);
HttpContext.Current.Cache.Insert(cacheKey, results, dependency);
return results;
}
return cachednews;
}
According to the stated Limitations for creating a query for notification, listed at msdn...
The statement must not reference a view.