How Do I create an autoincrement field in SQL and refer back? - sql

I am creating a flask backend that saves details of a DND style character on an SQL server. This is the application script for the input of the character details.
#app.route("/add_char", methods=["GET", "POST"])
#login_required
def add_char():
if request.method == "POST":
cha_id = db.execute("""INSERT INTO
character_basics (
char_id, user_id, name, race, cha_class, level, experience, alignment_lc, alignment_ge,
height, weight, handedness, eye_colour, hair_colour, sex, age, status,
max_hp, current_hp, strength, dexterity, constitution, intelligence,
wisdom, charisma, fortune
) VALUES (
:char_id, :user_id, :name, :race, :cha_class, :level, :experience, :alignment_lc, :alignment_ge,
:height, :weight, :handedness, :eye_colour, :hair_colour, :sex, :age, :status,
:max_hp, :current_hp, :strength, :dexterity, :constitution, :intelligence,
:wisdom, :charisma, :fortune
)
""",
user_id = session["user_id"],
name = request.form.get("name"),
race = request.form.get("race"),
cha_class = request.form.get("cha_class"),
level = request.form.get("level"),
experience = request.form.get("experience"),
alignment_lc = request.form.get("alignment_lc"),
alignment_ge = request.form.get("alignment_ge"),
height = request.form.get("height"),
weight = request.form.get("weight"),
handedness = request.form.get("handedness"),
eye_colour = request.form.get("eye_colour"),
hair_colour = request.form.get("hair_colour"),
sex = request.form.get("sex"),
age = request.form.get("age"),
status = request.form.get("status"),
max_hp = request.form.get("max_hp"),
current_hp = request.form.get("current_hp"),
strength = request.form.get("strength"),
dexterity = request.form.get("dexterity"),
constitution = request.form.get("constitution"),
intelligence = request.form.get("intelligence"),
wisdom = request.form.get("wisdom"),
charisma = request.form.get("charisma"),
fortune = request.form.get("fortune")
)
db.execute("""INSERT into
char_academic (
cha_id, anatomy, anatomy_basic, animal_lore, animal_lore_spec,
appraisal, appraisal_spec, arcana, arcana_spec, botany_forestry,
botany_spec, engineering, engineering_spec, history, history_spec,
mathematics, mathematics_spec, religion, religion_spec
) VALUES (
:cha_id, :anatomy, :anatomy_spec, :animal_lore, :animal_lore_spec,
:appraisal, :appraisal_spec, :arcana, :arcana_spec, :botany_foresty,
:botany_spec, :engineering, :engineering_spec, :history, :history_spec,
:mathematics, :mathematics_spec, :religion, :religion_spec
)
""",
anatomy = request.form.get("anatomy"),
anatomy_spec = request.form.get("anatomy_spec"),
animal_lore = request.form.get("animal_lore"),
animal_lore_spec = request.form.get("animal_lore_spec"),
appraisal = request.form.get("appraisal"),
appraisal_spec = request.form.get("appraisal_spec"),
arcana = request.form.get("arcana"),
arcana_spec = request.form.get("arcana_spec"),
botany_forestry = request.form.get("botany_forestry"),
botany_spec = request.form.get("botany_spec"),
engineering = request.form.get("engineering"),
engineering_spec = request.form.get("engineering_spec"),
history = request.form.get("history"),
histroy_spec = request.form.get("history_spec"),
mathematics = request.form.get("mathematics"),
mathematics_spec = request.form.get("mathematics_spec"),
religion = request.form.get("religion"),
religion_spec = request.form.get("religion_spec")
)
db.execute("""INSERT into
char_profession (
char_id, agriculture, agriculture_spec, blacksmithing,
blacksmithing_spec, commerce, commerce_spec, jeweller,
jeweller_spec, leather_working, leather_spec, masonry,
masonry_spec, metal_working, metal_working_spec, sailing,
sailing_spec, tailoring, tailoring_spec, woodworking,
woodworking_spec
) VALUES (
:char_id, :agriculture, :agriculture_spec, :blacksmithing,
:blacksmithing_spec, :commerce, :commerce_spec, :jeweller,
:jeweller_spec, :leather_working, :leather_spec, :masonry,
:masonry_spec, :metal_working, :metal_working_spec, :sailing,
:sailing_spec, :tailoring, :tailoring_spec, :woodworking,
:woodworking_spec
)
""",
agriculture = request.form.get("agriculture"),
agriculture_spec = request.form.get("agriculture_spec"),
blacksmithing = request.form.get("blacksmithing"),
blacksmithing_spec = request.form.get("blacksmithing_spec"),
commerce = request.form.get("commerce"),
commerce_spec = request.form.get("commerce_spec"),
jeweller = request.form.get("jeweller"),
jeweller_spec = request.form.get("jeweller_spec"),
leather_working = request.form.get("leather_working"),
leather_spec = request.form.get("leather_spec"),
masonry = request.form.get("masonry"),
masonry_spec = request.form.get("masonry_spec"),
metal_working = request.form.get("metal_working"),
metal_working_spec = request.form.get("metal_working_spec"),
sailing = request.form.get("sailing"),
sailing_spec = request.form.get("sailing_spec"),
tailoring = request.form.get("tailoring"),
tailoring_spec = request.form.get("tailoring_spec"),
woodworking = request.form.get("woodworking"),
woodworking_spec = request.form.get("woodworking_spec")
)
db.execute("""INSERT into
cha_gen_skills (
cha_id, acrobatics, acrobatics_spec, culture, culture_spec,
dancing, dancing_spec, first_aid, first_aid_spec,
manual_labour, labour_spec, musical_ability, music_spec,
observation, observation_spec, sleight, sleight_spec,
sneak, sneak_spec, social_interaction, social_spec, tracking,
tracking_spec, upkeep_maintenance, upkeep_spec
) VALUES (
:cha_id, :acrobatics, :acrobatics_spec, :culture, :culture_spec,
:dancing, :dancing_spec, :first_aid, :first_aid_spec,
:manual_labour, :labour_spec, :musical_ability, :music_spec,
:observation, :observation_spec, :sleight, :sleight_spec,
:sneak, :sneak_spec, :social_interaction, :social_spec, :tracking,
:tracking_spec, :upkeep_maintenance, :upkeep_spec
)
""",
acrobatics = request.form.get("acrobatics"),
acrobatics_spec = request.form.get("acrobatics_spec"),
culture = request.form.get("culture"),
culture_spec = request.form.get("culture_spec"),
dancing = request.form.get("dancing"),
dancing_spec = request.form.get("dancing_spec"),
first_aid = request.form.get("first_aid"),
first_aid_spec = request.form.get("first_aid_spec"),
manual_labour = request.form.get("manual_labour"),
labour_spec = request.form.get("labour_spec"),
musical_ability = request.form.get("musical_ability"),
muscic_spec = request.form.get("music_spec"),
observation = request.form.get("observation"),
observation_spec = request.form.get("observation_spec"),
sleight = request.form.get("sleight"),
sleight_spec = request.form.get("sleight_spec"),
sneak = request.form.get("sneak"),
sneak_spec = request.form.get("sneak_spec"),
social_interaction = request.form.get("social_interaction"),
social_spec = request.form.get("social_spec"),
tracking = request.form.get("tracking"),
tracking_spec = request.form.get("tracking_spec"),
upkeep_maintenance = request.form.get("upkeep_maintenance"),
upkeep = request.form.get("upkeep_spec")
)
db.execute("""INSERT into
cha_lang_skills (
cha_id, common, common_spec, dwarven, dwarven_spec, elvish,
elvish_spec, gnomeish, gnomeish_spec, halfling, halfling_spec
) VALUES (
:cha_id, :common, :common_spec, :dwarven, :dwarven_spec, :elvish,
:elvish_spec, :gnomeish, :gnomeish_spec, :halfling, :halfling_spec
)
""",
common = request.form.get("common"),
common_spec = request.form.get("common_spec"),
dwarven = request.form.get("dwarven"),
dwarven_spec = request.form.get("dwarven_spec"),
elvish = request.form.get("elvish"),
elvish_spec = request.form.get("elvish_spec"),
gnomeish = request.form.get("gnomeish"),
gnomeish_spec = request.form.get("gnomeish_spec"),
halfling = request.form.get("halfling_spec")
)
As far as I Understand it, the first section of code creates the cha_id but then how do I call it back for the subsequent calls?
These are the SQL tables...
-- Table structure for character_basics
----
CREATE TABLE 'character_basics' ('char_id' integer PRIMARY KEY AUTOINCREMENT NOT NULL, 'user_id' integer NOT NULL, 'name' text NOT NULL, 'race' text NOT NULL, 'cha_class' text NOT NULL, 'level' integer NOT NULL, 'experience' integer NOT NULL, 'alignment_lc' text NOT NULL, 'alignment_ge' text NOT NULL, 'height' integer NOT NULL, 'weight' integer NOT NULL, 'handedness' text NOT NULL, 'eye_colour' text NOT NULL, 'hair_colour' text NOT NULL, 'sex' text NOT NULL, 'age' integer NOT NULL, 'status' text NOT NULL, 'max_hp' integer NOT NULL, 'current_hp' integer NOT NULL, 'strength' integer NOT NULL, 'dexterity' integer NOT NULL, 'constitution' integer NOT NULL, 'intelligence' integer NOT NULL, 'wisdom' integer NOT NULL, 'charisma' integer NOT NULL, 'fortune' INTEGER NOT NULL );
----
-- Table structure for char_profession
----
CREATE TABLE 'char_profession' ('char_id' integer PRIMARY KEY NOT NULL, 'agriculture' integer NOT NULL, 'agriculture_spec' text, 'blacksmithing' integer NOT NULL, 'blacksmithing_spec' text, 'commerce' integer NOT NULL, 'commerce_spec' text, 'jeweller' integer NOT NULL, 'jeweller_spec' text, 'leather_working' integer NOT NULL, 'leather_spec' text, 'masonry' integer NOT NULL, 'masonry_spec' text, 'metal_working' integer NOT NULL, 'metal_working_spec' text, 'sailing' integer NOT NULL, 'sailing_spec' text, 'tailoring' integer NOT NULL, 'tailoring_spec' text, 'woodworking' INTEGER NOT NULL , 'woodworking_spec' text);
----
-- Table structure for cha_gen_skills
----
CREATE TABLE 'cha_gen_skills' ('char_id' integer NOT NULL, 'acrobatics' integer NOT NULL, 'acrobatics_spec' text, 'culture' integer NOT NULL, 'culture_spec' text, 'dancing' integer NOT NULL, 'dancing_spec' text, 'first_aid' integer NOT NULL, 'first_aid_spec' text, 'manual_labour' integer NOT NULL, 'labour_spec' text, 'musical_ability' integer NOT NULL, 'music_spec' text, 'observation' integer NOT NULL, 'observation_spec' text, 'sleight' integer NOT NULL, 'sleight_spec' text, 'sneak' integer NOT NULL, 'sneak_spec' text, 'social_interaction' integer NOT NULL, 'social_spec' text, 'tracking' integer NOT NULL, 'tracking_spec' text, 'upkeep_maintenance' integer NOT NULL, 'upkeep_spec' text);
----
-- Table structure for char_academic
----
CREATE TABLE 'char_academic' ('char_id' integer PRIMARY KEY NOT NULL, 'anatomy' integer NOT NULL, 'anatomy_spec' text, 'animal_lore' integer NOT NULL, 'animal_lore_spec' text, 'arcana' integer NOT NULL, 'arcana_spec' text, 'botany_forestry' integer NOT NULL, 'botany_spec' text, 'engineering' integer NOT NULL, 'engineering_spec' text, 'history' integer NOT NULL, 'history_spec' text, 'appraisal' INTEGER NOT NULL , 'appraisal_spec' text, 'mathematics' INTEGER NOT NULL , 'mathematic_spec' text, 'religion' INTEGER NOT NULL , 'religion_spec' text);
Thanks
Ed

Related

Using SELECT within Trigger

A customer needs a trigger for his new management tool. It works so far, but now he wants to get values from another table.
What does it mean? Take a short look at the (working) trigger:
CREATE OR REPLACE TRIGGER reldb_export_T_Import3_In
AFTER UPDATE OR INSERT OR DELETE ON infor.RELDB
FOR EACH ROW
DECLARE KST varchar(1000 BYTE);
BEGIN
IF (:new.ZUST = 4 AND :old.ZUST = 3 AND :old.SAINT = 60)
THEN
INSERT INTO infor2infoboard.T_Import3_In
(Idx, Timestamp, ObjectId, Text, RowUid, GroupName, GroupIndex, PredTimeCondition, PredGapValue, Service, ReqQuan, ReqDur,
Efficiency, BackColor, HighlightColor, Brightness, CellOffsetY, Fixed, Font, FontColor, Height, EarliestStart, LastDeliveryDate, RoleId,
StatusIds, WithReservation, LastChange, LastEditedBy, Opacity, IsProcess, CheckSymbol, Link, Priority, IconPath, Adress, CA1, CA2,
CA3, CA4, CA5, CA6, CA7, CA8, CA9, CA10, CA11, CA12, CA13, CA14, CA15,
CA16, CA17, CA18, CA19, CA20, CA21, CA22, CA23, CA24, CA25,
CA26, CA27, CA28, CA29, CA30, CA31, CA32)
VALUES
(seq_t_import3_in.nextval, sysdate, :old.RNR, NULL, CASE WHEN :NEW.KST = '3710' THEN 'Pool TB-M 1;Pool TB-M 2;Pool TB-M 3;Pool TB-M 4;Pool TB-M 5' ELSE KST END, :old.Komm, NULL, NULL, NULL, :old.KTXT, :old.TA_4, NULL,
NULL, CASE WHEN :new.MNR = '3740' THEN 'GREEN' WHEN :new.MNR != '3740' THEN 'BLUE' END, NULL, NULL, NULL, NULL, NULL, NULL, NULL, :old.TERM_2, :old.TERM_1, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, SUBSTR(:old.ANR, 1, 10), :old.KOMM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL);
END IF;......
Now he want to replace one of the last NULLS with a selected value.
The statement should look like this:
SELECT KTXT FROM RELDB WHERE ANR = :old.ANR and SAEXT = 'H';
So, for example:
NULL, (SELECT KTXT FROM RELDB WHERE ANR = :old.ANR and SAEXT = 'H';), SUBSTR(:old.ANR, 1, 10), :old.KOMM, NULL
My problem: I'm getting an error, that the trigger couldn't notice some changes. The trigger won't get fired.
So does anyone know how I can use or how I can get selected values (from the same (!!!) table which the trigger is listening to?
I'd appreciate your help :)
Cheers,
Dom
In Oracle, you cannot select from the same table you are changing, this is the mutating table error. See https://asktom.oracle.com/pls/apex/f?p=100:11:0::::p11_question_id:9579487119866

How to get an error message in R when trying to enter a duplicated key in a MySQL table?

Take a SQL table defined by:
CREATE TABLE `raw_dummy_code` (
`code` int DEFAULT NULL,
`description` text COLLATE utf8_unicode_ci,
`datestart` date DEFAULT NULL,
`dateend` date DEFAULT NULL,
UNIQUE KEY `code` (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
and a R data frame defined by:
raw_dummy_code <- data.frame(code = c(4, 4L, 4L),
datestart = c("2001-01-01", "2002-01-01", "2002-01-01"),
dateend = c("2001-12-31", "2500-01-01", "2500-01-01"),
description = c("old","recent","recent"),
stringsAsFactors = FALSE)
When I try to insert the data frame in the database :
con <- RMySQL::dbConnect(RMySQL::MySQL(), dbname = "test")
RMySQL::dbWriteTable(con, "raw_dummy_code", raw_dummy_code, row.names = FALSE, append = TRUE)
RMySQL::dbDisconnect(con)
RMySQL::dbWriteTable inserts only one row in the database. This is normal, since there are duplicated rows, but the problem is that there is no error message returned.
How to get the error message from MySQL when trying to enter a duplicated key?

PhoneGap sql checking for duplicates

I want to input a query to check the database for duplicate when inserting data into the database so it would prevent the activity Name from being entered more than once in a database
function insertQueryDB(tx) {
var myDB = window.openDatabase("test", "1.0", "Test DB", 1000000);
tx.executeSql('CREATE TABLE IF NOT EXISTS dataEntryTb (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, activityName TEXT NOT NULL, location TEXT NOT NULL, time NOT NULL, date NOT NULL, reporter NOT NULL)');
var an = document.forms["myForm"]["activityName"].value;
var l = document.forms["myForm"]["location"].value;
var t = document.forms["myForm"]["time"].value;
var d = document.forms["myForm"]["date"].value;
var r = document.forms["myForm"]["reporter"].value;
var query = 'INSERT INTO dataEntryTb ( activityName, location, time, date, reporter) VALUES ( "'+an+'", "'+l+'", "'+t+'", "'+d+'", "'+r+'")';
navigator.notification.alert("Retrieved the following: Activity Name="+an+" and Location="+l);
tx.executeSql(query,[]);
}``
Create the table with name being unique:
CREATE TABLE IF NOT EXISTS dataEntryTb (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
activityName TEXT NOT NULL UNIQUE,
location TEXT NOT NULL,
time NOT NULL, date NOT NULL,
reporter NOT NULL
);
Then the database will return an error if the name is already in the table.

How to sort Microsoft Azure database table data BY DATE

I am trying to sort the rows in my table by the latest date first.
var userParkingHistory = from j in dataGateway.SelectAll() select j ;
userParkingHistory = userParkingHistory.Where(ParkingHistory => ParkingHistory.username == User.Identity.Name);
return View(userParkingHistory);
I can currently display the rows sorted by the username but I also want it to sort by the latest date first.
In my gateway, this is how I select the list:
public IEnumerable<T> SelectAll()
{
return data.ToList();
}
Where and How do I sort the data according to the latest date first ?
This is how I define my table:
CREATE TABLE [dbo].[ParkingHistory] (
[parkingHistoryId] INT IDENTITY (1, 1) NOT NULL,
[carparkId] INT NULL,
[username] VARCHAR (255) NULL,
[date] DATETIME NULL,
[description] VARCHAR (255) NULL,
PRIMARY KEY CLUSTERED ([parkingHistoryId] ASC)
);
Linq has orderby:
var userParkingHistory = from j orderby j.date in dataGateway.SelectAll() select j ;
Alsi, List has various extension methods to sort itself.
Try this:
var userParkingHistory = dataGateway.SelectAll().Where(p => p.username == User.Identity.Name).OrderBy(p => p.date).ToList();
return View(userParkingHistory);

Django: make auth_user.email case-insensitive unique and nullable

I want to make the auth_user.email case-insensitive unique, nullable and default null. The following almost works:
from django.db.models.signals import post_syncdb
import app.models
SQLITE_AUTH_REFORM = [
"PRAGMA writable_schema = 1;",
"""UPDATE SQLITE_MASTER SET SQL =
'CREATE TABLE auth_user (
"id" integer NOT NULL PRIMARY KEY,
"username" varchar(30) NOT NULL UNIQUE,
"first_name" varchar(30) NOT NULL,
"last_name" varchar(30) NOT NULL,
"email" varchar(75) DEFAULT NULL,
"password" varchar(128) NOT NULL,
"is_staff" bool NOT NULL,
"is_active" bool NOT NULL,
"is_superuser" bool NOT NULL,
"last_login" datetime NOT NULL,
"date_joined" datetime NOT NULL
)' WHERE NAME = 'auth_user';""",
"PRAGMA writable_schema = 0;",
]
def post_syncdb_callback(sender, **kwargs):
from django.db import connections
from django.conf import settings
cursor = connections['default'].cursor()
if 'sqlite' in settings.DATABASES['default']['ENGINE']:
for stmt in SQLITE_AUTH_REFORM:
cursor.execute(stmt)
cursor.execute(
"CREATE UNIQUE INDEX IF NOT EXISTS auth_user_email_unique "
"ON auth_user (email COLLATE NOCASE);"
)
else: # Oracle
cursor.execute(
"CREATE UNIQUE INDEX auth_user_email_unique "
"ON auth_user (upper(email));"
)
cursor.cursor.close()
post_syncdb.connect(post_syncdb_callback, sender=app.models)
I can
User.objects.create(username=str(random.random()), email=None)
To my heart's content. And also,
User.objects.create(username=str(random.random()), email='Foo')
User.objects.create(username=str(random.random()), email='foo')
...
IntegrityError: column email is not unique
The only problems is that the DEFAULT NULL does not seem to work: User.objects.create(username=str(random.random())) creates a user with an empty-string email.
However, in a unit-test, I believe something is going on that prevents the post-syncdb hook from working:
class DjangoUserTest(TestCase):
def test_unique_nullable_email(self):
import IPython; IPython.embed()
u1 = User.objects.create(username="u1", email=None)
u2 = User.objects.create(username="u2", email=None)
I can drop into the ipython shell and see that the table has been apparently modified:
In [1]: from django.db import connection
In [2]: c = connection.cursor()
In [3]: r = c.execute("select `sql` from sqlite_master WHERE tbl_name = 'auth_user';")
In [4]: r.fetchall()
Out[4]:
[(u'CREATE TABLE auth_user (\n "id" integer NOT NULL PRIMARY KEY,\n "username" varchar(30) NOT NULL UNIQUE,\n "first_name" varchar(30) NOT NULL,\n "last_name" varchar(30) NOT NULL,\n "email" varchar(75) DEFAULT NULL,\n "password" varchar(128) NOT NULL,\n "is_staff" bool NOT NULL,\n "is_active" bool NOT NULL,\n "is_superuser" bool NOT NULL,\n "last_login" datetime NOT NULL,\n "date_joined" datetime NOT NULL\n)',),
(None,),
(u'CREATE UNIQUE INDEX auth_user_email_unique ON auth_user (email COLLATE NOCASE)',)]
However, upon trying to do the creates, I get, IntegrityError: auth_user.email may not be NULL. How did this happen when the select sql from sqlite_master WHERE tbl_name = 'auth_user'; clearly says "email" varchar(75) DEFAULT NULL. I feel like I just need to commit the post_syncdb stuff or sth. Any ideas?
UPDATE: No amount of connection.commit(), cursor.close() helps, using TransactionTestCase does not help.