*/
private bool mainSimpleSort(CompressionState dataShadow, int lo,
- int hi, int d)
- {
+ int hi, int d) {
int bigN = hi - lo + 1;
- if (bigN < 2)
- {
+ if (bigN < 2) {
return this.firstAttempt && (this.workDone > this.workLimit);
}
@@ -727,16 +674,13 @@ private bool mainSimpleSort(CompressionState dataShadow, int lo,
// coding it in additional loops.
// HP:
- while (--hp >= 0)
- {
+ while (--hp >= 0) {
int h = increments[hp];
int mj = lo + h - 1;
- for (int i = lo + h; i <= hi;)
- {
+ for (int i = lo + h; i <= hi;) {
// copy
- for (int k = 3; (i <= hi) && (--k >= 0); i++)
- {
+ for (int k = 3; (i <= hi) && (--k >= 0); i++) {
int v = fmap[i];
int vd = v + d;
int j = i;
@@ -754,17 +698,13 @@ private bool mainSimpleSort(CompressionState dataShadow, int lo,
bool onceRunned = false;
int a = 0;
- HAMMER: while (true)
- {
- if (onceRunned)
- {
+ HAMMER: while (true) {
+ if (onceRunned) {
fmap[j] = a;
- if ((j -= h) <= mj)
- {
+ if ((j -= h) <= mj) {
goto END_HAMMER;
}
- }
- else {
+ } else {
onceRunned = true;
}
@@ -774,111 +714,70 @@ private bool mainSimpleSort(CompressionState dataShadow, int lo,
// following could be done in a loop, but
// unrolled it for performance:
- if (block[i1 + 1] == block[i2 + 1])
- {
- if (block[i1 + 2] == block[i2 + 2])
- {
- if (block[i1 + 3] == block[i2 + 3])
- {
- if (block[i1 + 4] == block[i2 + 4])
- {
- if (block[i1 + 5] == block[i2 + 5])
- {
- if (block[(i1 += 6)] == block[(i2 += 6)])
- {
+ if (block[i1 + 1] == block[i2 + 1]) {
+ if (block[i1 + 2] == block[i2 + 2]) {
+ if (block[i1 + 3] == block[i2 + 3]) {
+ if (block[i1 + 4] == block[i2 + 4]) {
+ if (block[i1 + 5] == block[i2 + 5]) {
+ if (block[(i1 += 6)] == block[(i2 += 6)]) {
int x = lastShadow;
- X: while (x > 0)
- {
+ X: while (x > 0) {
x -= 4;
- if (block[i1 + 1] == block[i2 + 1])
- {
- if (quadrant[i1] == quadrant[i2])
- {
- if (block[i1 + 2] == block[i2 + 2])
- {
- if (quadrant[i1 + 1] == quadrant[i2 + 1])
- {
- if (block[i1 + 3] == block[i2 + 3])
- {
- if (quadrant[i1 + 2] == quadrant[i2 + 2])
- {
- if (block[i1 + 4] == block[i2 + 4])
- {
- if (quadrant[i1 + 3] == quadrant[i2 + 3])
- {
- if ((i1 += 4) >= lastPlus1)
- {
+ if (block[i1 + 1] == block[i2 + 1]) {
+ if (quadrant[i1] == quadrant[i2]) {
+ if (block[i1 + 2] == block[i2 + 2]) {
+ if (quadrant[i1 + 1] == quadrant[i2 + 1]) {
+ if (block[i1 + 3] == block[i2 + 3]) {
+ if (quadrant[i1 + 2] == quadrant[i2 + 2]) {
+ if (block[i1 + 4] == block[i2 + 4]) {
+ if (quadrant[i1 + 3] == quadrant[i2 + 3]) {
+ if ((i1 += 4) >= lastPlus1) {
i1 -= lastPlus1;
}
- if ((i2 += 4) >= lastPlus1)
- {
+ if ((i2 += 4) >= lastPlus1) {
i2 -= lastPlus1;
}
workDoneShadow++;
goto X;
- }
- else if ((quadrant[i1 + 3] > quadrant[i2 + 3]))
- {
+ } else if ((quadrant[i1 + 3] > quadrant[i2 + 3])) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 4] & 0xff) > (block[i2 + 4] & 0xff))
- {
+ } else if ((block[i1 + 4] & 0xff) > (block[i2 + 4] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((quadrant[i1 + 2] > quadrant[i2 + 2]))
- {
+ } else if ((quadrant[i1 + 2] > quadrant[i2 + 2])) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 3] & 0xff) > (block[i2 + 3] & 0xff))
- {
+ } else if ((block[i1 + 3] & 0xff) > (block[i2 + 3] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((quadrant[i1 + 1] > quadrant[i2 + 1]))
- {
+ } else if ((quadrant[i1 + 1] > quadrant[i2 + 1])) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 2] & 0xff) > (block[i2 + 2] & 0xff))
- {
+ } else if ((block[i1 + 2] & 0xff) > (block[i2 + 2] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((quadrant[i1] > quadrant[i2]))
- {
+ } else if ((quadrant[i1] > quadrant[i2])) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 1] & 0xff) > (block[i2 + 1] & 0xff))
- {
+ } else if ((block[i1 + 1] & 0xff) > (block[i2 + 1] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
@@ -886,71 +785,53 @@ private bool mainSimpleSort(CompressionState dataShadow, int lo,
goto END_HAMMER;
} // while x > 0
else {
- if ((block[i1] & 0xff) > (block[i2] & 0xff))
- {
+ if ((block[i1] & 0xff) > (block[i2] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
}
- }
- else if ((block[i1 + 5] & 0xff) > (block[i2 + 5] & 0xff))
- {
+ } else if ((block[i1 + 5] & 0xff) > (block[i2 + 5] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 4] & 0xff) > (block[i2 + 4] & 0xff))
- {
+ } else if ((block[i1 + 4] & 0xff) > (block[i2 + 4] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 3] & 0xff) > (block[i2 + 3] & 0xff))
- {
+ } else if ((block[i1 + 3] & 0xff) > (block[i2 + 3] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 2] & 0xff) > (block[i2 + 2] & 0xff))
- {
+ } else if ((block[i1 + 2] & 0xff) > (block[i2 + 2] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
- }
- else if ((block[i1 + 1] & 0xff) > (block[i2 + 1] & 0xff))
- {
+ } else if ((block[i1 + 1] & 0xff) > (block[i2 + 1] & 0xff)) {
goto HAMMER;
- }
- else {
+ } else {
goto END_HAMMER;
}
} // HAMMER
- END_HAMMER:
+ END_HAMMER:
// end inline mainGTU
fmap[j] = v;
}
if (firstAttemptShadow && (i <= hi)
- && (workDoneShadow > workLimitShadow))
- {
+ && (workDoneShadow > workLimitShadow)) {
goto END_HP;
}
}
}
- END_HP:
+ END_HP:
this.workDone = workDoneShadow;
return firstAttemptShadow && (workDoneShadow > workLimitShadow);
@@ -958,19 +839,16 @@ private bool mainSimpleSort(CompressionState dataShadow, int lo,
- private static void vswap(int[] fmap, int p1, int p2, int n)
- {
+ private static void vswap(int[] fmap, int p1, int p2, int n) {
n += p1;
- while (p1 < n)
- {
+ while (p1 < n) {
int t = fmap[p1];
fmap[p1++] = fmap[p2];
fmap[p2++] = t;
}
}
- private static byte med3(byte a, byte b, byte c)
- {
+ private static byte med3(byte a, byte b, byte c) {
return (a < b) ? (b < c ? b : a < c ? c : a) : (b > c ? b : a > c ? c
: a);
}
@@ -980,8 +858,7 @@ private static byte med3(byte a, byte b, byte c)
* Method "mainQSort3", file "blocksort.c", BZip2 1.0.2
*/
private void mainQSort3(CompressionState dataShadow, int loSt,
- int hiSt, int dSt)
- {
+ int hiSt, int dSt) {
int[] stack_ll = dataShadow.stack_ll;
int[] stack_hh = dataShadow.stack_hh;
int[] stack_dd = dataShadow.stack_dd;
@@ -992,20 +869,16 @@ private void mainQSort3(CompressionState dataShadow, int loSt,
stack_hh[0] = hiSt;
stack_dd[0] = dSt;
- for (int sp = 1; --sp >= 0;)
- {
+ for (int sp = 1; --sp >= 0;) {
int lo = stack_ll[sp];
int hi = stack_hh[sp];
int d = stack_dd[sp];
- if ((hi - lo < SMALL_THRESH) || (d > DEPTH_THRESH))
- {
- if (mainSimpleSort(dataShadow, lo, hi, d))
- {
+ if ((hi - lo < SMALL_THRESH) || (d > DEPTH_THRESH)) {
+ if (mainSimpleSort(dataShadow, lo, hi, d)) {
return;
}
- }
- else {
+ } else {
int d1 = d + 1;
int med = med3(block[fmap[lo] + d1],
block[fmap[hi] + d1], block[fmap[(lo + hi) >> 1] + d1]) & 0xff;
@@ -1015,65 +888,50 @@ private void mainQSort3(CompressionState dataShadow, int loSt,
int ltLo = lo;
int gtHi = hi;
- while (true)
- {
- while (unLo <= unHi)
- {
+ while (true) {
+ while (unLo <= unHi) {
int n = (block[fmap[unLo] + d1] & 0xff)
- med;
- if (n == 0)
- {
+ if (n == 0) {
int temp = fmap[unLo];
fmap[unLo++] = fmap[ltLo];
fmap[ltLo++] = temp;
- }
- else if (n < 0)
- {
+ } else if (n < 0) {
unLo++;
- }
- else {
+ } else {
break;
}
}
- while (unLo <= unHi)
- {
+ while (unLo <= unHi) {
int n = (block[fmap[unHi] + d1] & 0xff)
- med;
- if (n == 0)
- {
+ if (n == 0) {
int temp = fmap[unHi];
fmap[unHi--] = fmap[gtHi];
fmap[gtHi--] = temp;
- }
- else if (n > 0)
- {
+ } else if (n > 0) {
unHi--;
- }
- else {
+ } else {
break;
}
}
- if (unLo <= unHi)
- {
+ if (unLo <= unHi) {
int temp = fmap[unLo];
fmap[unLo++] = fmap[unHi];
fmap[unHi--] = temp;
- }
- else {
+ } else {
break;
}
}
- if (gtHi < ltLo)
- {
+ if (gtHi < ltLo) {
stack_ll[sp] = lo;
stack_hh[sp] = hi;
stack_dd[sp] = d1;
sp++;
- }
- else {
+ } else {
int n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo)
: (unLo - ltLo);
vswap(fmap, lo, unLo - n, n);
@@ -1105,8 +963,7 @@ private void mainQSort3(CompressionState dataShadow, int loSt,
- private void generateMTFValues()
- {
+ private void generateMTFValues() {
int lastShadow = this.last;
CompressionState dataShadow = this.cstate;
bool[] inUse = dataShadow.inUse;
@@ -1119,11 +976,9 @@ private void generateMTFValues()
// make maps
int nInUseShadow = 0;
- for (int i = 0; i < 256; i++)
- {
- if (inUse[i])
- {
- unseqToSeq[i] = (byte) nInUseShadow;
+ for (int i = 0; i < 256; i++) {
+ if (inUse[i]) {
+ unseqToSeq[i] = (byte)nInUseShadow;
nInUseShadow++;
}
}
@@ -1131,27 +986,23 @@ private void generateMTFValues()
int eob = nInUseShadow + 1;
- for (int i = eob; i >= 0; i--)
- {
+ for (int i = eob; i >= 0; i--) {
mtfFreq[i] = 0;
}
- for (int i = nInUseShadow; --i >= 0;)
- {
- yy[i] = (byte) i;
+ for (int i = nInUseShadow; --i >= 0;) {
+ yy[i] = (byte)i;
}
int wr = 0;
int zPend = 0;
- for (int i = 0; i <= lastShadow; i++)
- {
+ for (int i = 0; i <= lastShadow; i++) {
byte ll_i = unseqToSeq[block[fmap[i]] & 0xff];
byte tmp = yy[0];
int j = 0;
- while (ll_i != tmp)
- {
+ while (ll_i != tmp) {
j++;
byte tmp2 = tmp;
tmp = yy[j];
@@ -1159,93 +1010,70 @@ private void generateMTFValues()
}
yy[0] = tmp;
- if (j == 0)
- {
+ if (j == 0) {
zPend++;
- }
- else
- {
- if (zPend > 0)
- {
+ } else {
+ if (zPend > 0) {
zPend--;
- while (true)
- {
- if ((zPend & 1) == 0)
- {
+ while (true) {
+ if ((zPend & 1) == 0) {
sfmap[wr] = BZip2.RUNA;
wr++;
mtfFreq[BZip2.RUNA]++;
- }
- else
- {
+ } else {
sfmap[wr] = BZip2.RUNB;
wr++;
mtfFreq[BZip2.RUNB]++;
}
- if (zPend >= 2)
- {
+ if (zPend >= 2) {
zPend = (zPend - 2) >> 1;
- }
- else
- {
+ } else {
break;
}
}
zPend = 0;
}
- sfmap[wr] = (char) (j + 1);
+ sfmap[wr] = (char)(j + 1);
wr++;
mtfFreq[j + 1]++;
}
}
- if (zPend > 0)
- {
+ if (zPend > 0) {
zPend--;
- while (true)
- {
- if ((zPend & 1) == 0)
- {
+ while (true) {
+ if ((zPend & 1) == 0) {
sfmap[wr] = BZip2.RUNA;
wr++;
mtfFreq[BZip2.RUNA]++;
- }
- else
- {
+ } else {
sfmap[wr] = BZip2.RUNB;
wr++;
mtfFreq[BZip2.RUNB]++;
}
- if (zPend >= 2)
- {
+ if (zPend >= 2) {
zPend = (zPend - 2) >> 1;
- }
- else
- {
+ } else {
break;
}
}
}
- sfmap[wr] = (char) eob;
+ sfmap[wr] = (char)eob;
mtfFreq[eob]++;
this.nMTF = wr + 1;
}
- private static void hbAssignCodes(int[] code, byte[] length,
+ private static void hbAssignCodes(int[] code, byte[] length,
int minLen, int maxLen,
- int alphaSize)
- {
+ int alphaSize) {
int vec = 0;
- for (int n = minLen; n <= maxLen; n++)
- {
- for (int i = 0; i < alphaSize; i++)
- {
- if ((length[i] & 0xff) == n)
- {
+ for (int n = minLen; n <= maxLen; n++) {
+ for (int i = 0; i < alphaSize; i++) {
+ if ((length[i] & 0xff) == n) {
code[i] = vec;
vec++;
}
@@ -1257,16 +1085,13 @@ private static void hbAssignCodes(int[] code, byte[] length,
- private void sendMTFValues()
- {
+ private void sendMTFValues() {
byte[][] len = this.cstate.sendMTFValues_len;
int alphaSize = this.nInUse + 2;
- for (int t = BZip2.NGroups; --t >= 0;)
- {
+ for (int t = BZip2.NGroups; --t >= 0;) {
byte[] len_t = len[t];
- for (int v = alphaSize; --v >= 0;)
- {
+ for (int v = alphaSize; --v >= 0;) {
len_t[v] = GREATER_ICOST;
}
}
@@ -1303,39 +1128,32 @@ private void sendMTFValues()
sendMTFValues7(nSelectors);
}
- private void sendMTFValues0(int nGroups, int alphaSize)
- {
+ private void sendMTFValues0(int nGroups, int alphaSize) {
byte[][] len = this.cstate.sendMTFValues_len;
int[] mtfFreq = this.cstate.mtfFreq;
int remF = this.nMTF;
int gs = 0;
- for (int nPart = nGroups; nPart > 0; nPart--)
- {
+ for (int nPart = nGroups; nPart > 0; nPart--) {
int tFreq = remF / nPart;
int ge = gs - 1;
int aFreq = 0;
- for (int a = alphaSize - 1; (aFreq < tFreq) && (ge < a);)
- {
+ for (int a = alphaSize - 1; (aFreq < tFreq) && (ge < a);) {
aFreq += mtfFreq[++ge];
}
if ((ge > gs) && (nPart != nGroups) && (nPart != 1)
- && (((nGroups - nPart) & 1) != 0))
- {
+ && (((nGroups - nPart) & 1) != 0)) {
aFreq -= mtfFreq[ge--];
}
byte[] len_np = len[nPart - 1];
- for (int v = alphaSize; --v >= 0;)
- {
- if ((v >= gs) && (v <= ge))
- {
+ for (int v = alphaSize; --v >= 0;) {
+ if ((v >= gs) && (v <= ge)) {
len_np[v] = LESSER_ICOST;
- }
- else {
+ } else {
len_np[v] = GREATER_ICOST;
}
}
@@ -1346,10 +1164,9 @@ private void sendMTFValues0(int nGroups, int alphaSize)
}
- private static void hbMakeCodeLengths(byte[] len, int[] freq,
+ private static void hbMakeCodeLengths(byte[] len, int[] freq,
CompressionState state1, int alphaSize,
- int maxLen)
- {
+ int maxLen) {
/*
* Nodes and heap entries run from 1. Entry 0 for both the heap and
* nodes is a sentinel.
@@ -1358,13 +1175,11 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
int[] weight = state1.weight;
int[] parent = state1.parent;
- for (int i = alphaSize; --i >= 0;)
- {
+ for (int i = alphaSize; --i >= 0;) {
weight[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
}
- for (bool tooLong = true; tooLong;)
- {
+ for (bool tooLong = true; tooLong;) {
tooLong = false;
int nNodes = alphaSize;
@@ -1373,24 +1188,21 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
weight[0] = 0;
parent[0] = -2;
- for (int i = 1; i <= alphaSize; i++)
- {
+ for (int i = 1; i <= alphaSize; i++) {
parent[i] = -1;
nHeap++;
heap[nHeap] = i;
int zz = nHeap;
int tmp = heap[zz];
- while (weight[tmp] < weight[heap[zz >> 1]])
- {
+ while (weight[tmp] < weight[heap[zz >> 1]]) {
heap[zz] = heap[zz >> 1];
zz >>= 1;
}
heap[zz] = tmp;
}
- while (nHeap > 1)
- {
+ while (nHeap > 1) {
int n1 = heap[1];
heap[1] = heap[nHeap];
nHeap--;
@@ -1399,23 +1211,19 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
int zz = 1;
int tmp = heap[1];
- while (true)
- {
+ while (true) {
yy = zz << 1;
- if (yy > nHeap)
- {
+ if (yy > nHeap) {
break;
}
if ((yy < nHeap)
- && (weight[heap[yy + 1]] < weight[heap[yy]]))
- {
+ && (weight[heap[yy + 1]] < weight[heap[yy]])) {
yy++;
}
- if (weight[tmp] < weight[heap[yy]])
- {
+ if (weight[tmp] < weight[heap[yy]]) {
break;
}
@@ -1433,23 +1241,19 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
zz = 1;
tmp = heap[1];
- while (true)
- {
+ while (true) {
yy = zz << 1;
- if (yy > nHeap)
- {
+ if (yy > nHeap) {
break;
}
if ((yy < nHeap)
- && (weight[heap[yy + 1]] < weight[heap[yy]]))
- {
+ && (weight[heap[yy + 1]] < weight[heap[yy]])) {
yy++;
}
- if (weight[tmp] < weight[heap[yy]])
- {
+ if (weight[tmp] < weight[heap[yy]]) {
break;
}
@@ -1463,7 +1267,7 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
int weight_n1 = weight[n1];
int weight_n2 = weight[n2];
- weight[nNodes] = (int) (((uint)weight_n1 & 0xffffff00U)
+ weight[nNodes] = (int)(((uint)weight_n1 & 0xffffff00U)
+ ((uint)weight_n2 & 0xffffff00U))
| (1 + (((weight_n1 & 0x000000ff)
> (weight_n2 & 0x000000ff))
@@ -1478,8 +1282,7 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
zz = nHeap;
tmp = heap[zz];
int weight_tmp = weight[tmp];
- while (weight_tmp < weight[heap[zz >> 1]])
- {
+ while (weight_tmp < weight[heap[zz >> 1]]) {
heap[zz] = heap[zz >> 1];
zz >>= 1;
}
@@ -1487,28 +1290,23 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
}
- for (int i = 1; i <= alphaSize; i++)
- {
+ for (int i = 1; i <= alphaSize; i++) {
int j = 0;
int k = i;
- for (int parent_k; (parent_k = parent[k]) >= 0;)
- {
+ for (int parent_k; (parent_k = parent[k]) >= 0;) {
k = parent_k;
j++;
}
- len[i - 1] = (byte) j;
- if (j > maxLen)
- {
+ len[i - 1] = (byte)j;
+ if (j > maxLen) {
tooLong = true;
}
}
- if (tooLong)
- {
- for (int i = 1; i < alphaSize; i++)
- {
+ if (tooLong) {
+ for (int i = 1; i < alphaSize; i++) {
int j = weight[i] >> 8;
j = 1 + (j >> 1);
weight[i] = j << 8;
@@ -1518,8 +1316,7 @@ private static void hbMakeCodeLengths(byte[] len, int[] freq,
}
- private int sendMTFValues1(int nGroups, int alphaSize)
- {
+ private int sendMTFValues1(int nGroups, int alphaSize) {
CompressionState dataShadow = this.cstate;
int[][] rfreq = dataShadow.sendMTFValues_rfreq;
int[] fave = dataShadow.sendMTFValues_fave;
@@ -1537,22 +1334,18 @@ private int sendMTFValues1(int nGroups, int alphaSize)
int nSelectors = 0;
- for (int iter = 0; iter < BZip2.N_ITERS; iter++)
- {
- for (int t = nGroups; --t >= 0;)
- {
+ for (int iter = 0; iter < BZip2.N_ITERS; iter++) {
+ for (int t = nGroups; --t >= 0;) {
fave[t] = 0;
int[] rfreqt = rfreq[t];
- for (int i = alphaSize; --i >= 0;)
- {
+ for (int i = alphaSize; --i >= 0;) {
rfreqt[i] = 0;
}
}
nSelectors = 0;
- for (int gs = 0; gs < this.nMTF;)
- {
+ for (int gs = 0; gs < this.nMTF;) {
/* Set group start & end marks. */
/*
@@ -1562,14 +1355,12 @@ private int sendMTFValues1(int nGroups, int alphaSize)
int ge = Math.Min(gs + BZip2.G_SIZE - 1, nMTFShadow - 1);
- if (nGroups == BZip2.NGroups)
- {
+ if (nGroups == BZip2.NGroups) {
// unrolled version of the else-block
int[] c = new int[6];
- for (int i = gs; i <= ge; i++)
- {
+ for (int i = gs; i <= ge; i++) {
int icv = sfmap[i];
c[0] += len_0[icv] & 0xff;
c[1] += len_1[icv] & 0xff;
@@ -1579,26 +1370,21 @@ private int sendMTFValues1(int nGroups, int alphaSize)
c[5] += len_5[icv] & 0xff;
}
- cost[0] = (short) c[0];
- cost[1] = (short) c[1];
- cost[2] = (short) c[2];
- cost[3] = (short) c[3];
- cost[4] = (short) c[4];
- cost[5] = (short) c[5];
- }
- else
- {
- for (int t = nGroups; --t >= 0;)
- {
+ cost[0] = (short)c[0];
+ cost[1] = (short)c[1];
+ cost[2] = (short)c[2];
+ cost[3] = (short)c[3];
+ cost[4] = (short)c[4];
+ cost[5] = (short)c[5];
+ } else {
+ for (int t = nGroups; --t >= 0;) {
cost[t] = 0;
}
- for (int i = gs; i <= ge; i++)
- {
+ for (int i = gs; i <= ge; i++) {
int icv = sfmap[i];
- for (int t = nGroups; --t >= 0;)
- {
- cost[t] += (short) (len[t][icv] & 0xff);
+ for (int t = nGroups; --t >= 0;) {
+ cost[t] += (short)(len[t][icv] & 0xff);
}
}
}
@@ -1608,26 +1394,23 @@ private int sendMTFValues1(int nGroups, int alphaSize)
* record its identity in the selector table.
*/
int bt = -1;
- for (int t = nGroups, bc = 999999999; --t >= 0;)
- {
+ for (int t = nGroups, bc = 999999999; --t >= 0;) {
int cost_t = cost[t];
- if (cost_t < bc)
- {
+ if (cost_t < bc) {
bc = cost_t;
bt = t;
}
}
fave[bt]++;
- selector[nSelectors] = (byte) bt;
+ selector[nSelectors] = (byte)bt;
nSelectors++;
/*
* Increment the symbol frequencies for the selected table.
*/
int[] rfreq_bt = rfreq[bt];
- for (int i = gs; i <= ge; i++)
- {
+ for (int i = gs; i <= ge; i++) {
rfreq_bt[sfmap[i]]++;
}
@@ -1637,8 +1420,7 @@ private int sendMTFValues1(int nGroups, int alphaSize)
/*
* Recompute the tables based on the accumulated frequencies.
*/
- for (int t = 0; t < nGroups; t++)
- {
+ for (int t = 0; t < nGroups; t++) {
hbMakeCodeLengths(len[t], rfreq[t], this.cstate, alphaSize, 20);
}
}
@@ -1646,26 +1428,22 @@ private int sendMTFValues1(int nGroups, int alphaSize)
return nSelectors;
}
- private void sendMTFValues2(int nGroups, int nSelectors)
- {
+ private void sendMTFValues2(int nGroups, int nSelectors) {
// assert (nGroups < 8) : nGroups;
CompressionState dataShadow = this.cstate;
byte[] pos = dataShadow.sendMTFValues2_pos;
- for (int i = nGroups; --i >= 0;)
- {
- pos[i] = (byte) i;
+ for (int i = nGroups; --i >= 0;) {
+ pos[i] = (byte)i;
}
- for (int i = 0; i < nSelectors; i++)
- {
+ for (int i = 0; i < nSelectors; i++) {
byte ll_i = dataShadow.selector[i];
byte tmp = pos[0];
int j = 0;
- while (ll_i != tmp)
- {
+ while (ll_i != tmp) {
j++;
byte tmp2 = tmp;
tmp = pos[j];
@@ -1673,29 +1451,24 @@ private void sendMTFValues2(int nGroups, int nSelectors)
}
pos[0] = tmp;
- dataShadow.selectorMtf[i] = (byte) j;
+ dataShadow.selectorMtf[i] = (byte)j;
}
}
- private void sendMTFValues3(int nGroups, int alphaSize)
- {
+ private void sendMTFValues3(int nGroups, int alphaSize) {
int[][] code = this.cstate.sendMTFValues_code;
byte[][] len = this.cstate.sendMTFValues_len;
- for (int t = 0; t < nGroups; t++)
- {
+ for (int t = 0; t < nGroups; t++) {
int minLen = 32;
int maxLen = 0;
byte[] len_t = len[t];
- for (int i = alphaSize; --i >= 0;)
- {
+ for (int i = alphaSize; --i >= 0;) {
int l = len_t[i] & 0xff;
- if (l > maxLen)
- {
+ if (l > maxLen) {
maxLen = l;
}
- if (l < minLen)
- {
+ if (l < minLen) {
minLen = l;
}
}
@@ -1707,43 +1480,34 @@ private void sendMTFValues3(int nGroups, int alphaSize)
}
}
- private void sendMTFValues4()
- {
+ private void sendMTFValues4() {
bool[] inUse = this.cstate.inUse;
bool[] inUse16 = this.cstate.sentMTFValues4_inUse16;
- for (int i = 16; --i >= 0;)
- {
+ for (int i = 16; --i >= 0;) {
inUse16[i] = false;
int i16 = i * 16;
- for (int j = 16; --j >= 0;)
- {
- if (inUse[i16 + j])
- {
+ for (int j = 16; --j >= 0;) {
+ if (inUse[i16 + j]) {
inUse16[i] = true;
}
}
}
uint u = 0;
- for (int i = 0; i < 16; i++)
- {
+ for (int i = 0; i < 16; i++) {
if (inUse16[i])
u |= 1U << (16 - i - 1);
}
this.bw.WriteBits(16, u);
- for (int i = 0; i < 16; i++)
- {
- if (inUse16[i])
- {
+ for (int i = 0; i < 16; i++) {
+ if (inUse16[i]) {
int i16 = i * 16;
u = 0;
- for (int j = 0; j < 16; j++)
- {
- if (inUse[i16 + j])
- {
+ for (int j = 0; j < 16; j++) {
+ if (inUse[i16 + j]) {
u |= 1U << (16 - j - 1);
}
}
@@ -1753,17 +1517,14 @@ private void sendMTFValues4()
}
- private void sendMTFValues5(int nGroups, int nSelectors)
- {
- this.bw.WriteBits(3, (uint) nGroups);
- this.bw.WriteBits(15, (uint) nSelectors);
+ private void sendMTFValues5(int nGroups, int nSelectors) {
+ this.bw.WriteBits(3, (uint)nGroups);
+ this.bw.WriteBits(15, (uint)nSelectors);
byte[] selectorMtf = this.cstate.selectorMtf;
- for (int i = 0; i < nSelectors; i++)
- {
- for (int j = 0, hj = selectorMtf[i] & 0xff; j < hj; j++)
- {
+ for (int i = 0; i < nSelectors; i++) {
+ for (int j = 0, hj = selectorMtf[i] & 0xff; j < hj; j++) {
this.bw.WriteBits(1, 1);
}
@@ -1771,27 +1532,22 @@ private void sendMTFValues5(int nGroups, int nSelectors)
}
}
- private void sendMTFValues6(int nGroups, int alphaSize)
- {
+ private void sendMTFValues6(int nGroups, int alphaSize) {
byte[][] len = this.cstate.sendMTFValues_len;
- for (int t = 0; t < nGroups; t++)
- {
+ for (int t = 0; t < nGroups; t++) {
byte[] len_t = len[t];
- uint curr = (uint) (len_t[0] & 0xff);
+ uint curr = (uint)(len_t[0] & 0xff);
this.bw.WriteBits(5, curr);
- for (int i = 0; i < alphaSize; i++)
- {
+ for (int i = 0; i < alphaSize; i++) {
int lti = len_t[i] & 0xff;
- while (curr < lti)
- {
+ while (curr < lti) {
this.bw.WriteBits(2, 2U);
curr++; /* 10 */
}
- while (curr > lti)
- {
+ while (curr > lti) {
this.bw.WriteBits(2, 3U);
curr--; /* 11 */
}
@@ -1802,28 +1558,25 @@ private void sendMTFValues6(int nGroups, int alphaSize)
}
- private void sendMTFValues7(int nSelectors)
- {
- byte[][] len = this.cstate.sendMTFValues_len;
- int[][] code = this.cstate.sendMTFValues_code;
+ private void sendMTFValues7(int nSelectors) {
+ byte[][] len = this.cstate.sendMTFValues_len;
+ int[][] code = this.cstate.sendMTFValues_code;
byte[] selector = this.cstate.selector;
- char[] sfmap = this.cstate.sfmap;
- int nMTFShadow = this.nMTF;
+ char[] sfmap = this.cstate.sfmap;
+ int nMTFShadow = this.nMTF;
int selCtr = 0;
- for (int gs = 0; gs < nMTFShadow;)
- {
+ for (int gs = 0; gs < nMTFShadow;) {
int ge = Math.Min(gs + BZip2.G_SIZE - 1, nMTFShadow - 1);
int ix = selector[selCtr] & 0xff;
int[] code_selCtr = code[ix];
byte[] len_selCtr = len[ix];
- while (gs <= ge)
- {
+ while (gs <= ge) {
int sfmap_i = sfmap[gs];
int n = len_selCtr[sfmap_i] & 0xFF;
- this.bw.WriteBits(n, (uint) code_selCtr[sfmap_i]);
+ this.bw.WriteBits(n, (uint)code_selCtr[sfmap_i]);
gs++;
}
@@ -1832,9 +1585,8 @@ private void sendMTFValues7(int nSelectors)
}
}
- private void moveToFrontCodeAndSend()
- {
- this.bw.WriteBits(24, (uint) this.origPtr);
+ private void moveToFrontCodeAndSend() {
+ this.bw.WriteBits(24, (uint)this.origPtr);
generateMTFValues();
sendMTFValues();
}
@@ -1844,8 +1596,7 @@ private void moveToFrontCodeAndSend()
- private class CompressionState
- {
+ private class CompressionState {
// with blockSize 900k
public readonly bool[] inUse = new bool[256]; // 256 byte
public readonly byte[] unseqToSeq = new byte[256]; // 256 byte
@@ -1899,16 +1650,15 @@ private class CompressionState
*/
public char[] quadrant;
- public CompressionState(int blockSize100k)
- {
+ public CompressionState(int blockSize100k) {
int n = blockSize100k * BZip2.BlockSizeMultiple;
this.block = new byte[(n + 1 + BZip2.NUM_OVERSHOOT_BYTES)];
this.fmap = new int[n];
this.sfmap = new char[2 * n];
this.quadrant = this.sfmap;
- this.sendMTFValues_len = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
- this.sendMTFValues_rfreq = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
- this.sendMTFValues_code = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
+ this.sendMTFValues_len = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
+ this.sendMTFValues_rfreq = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
+ this.sendMTFValues_code = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
}
}
diff --git a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2InputStream.cs b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2InputStream.cs
index 113d139aa..19f075e91 100644
--- a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2InputStream.cs
+++ b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2InputStream.cs
@@ -57,14 +57,12 @@
using System;
using System.IO;
-namespace Ionic.BZip2
-{
+namespace Ionic.BZip2 {
///
/// A read-only decorator stream that performs BZip2 decompression on Read.
///
- public class BZip2InputStream : System.IO.Stream
- {
+ public class BZip2InputStream : System.IO.Stream {
private bool _disposed;
private bool _leaveOpen;
private Int64 totalBytesRead;
@@ -89,8 +87,7 @@ public class BZip2InputStream : System.IO.Stream
///
/// Compressor State
///
- private enum CState
- {
+ private enum CState {
EOF = 0,
START_BLOCK = 1,
RAND_PART_A = 2,
@@ -129,8 +126,7 @@ private enum CState
///
/// The stream from which to read compressed data
public BZip2InputStream(Stream input)
- : this(input, false)
- {}
+ : this(input, false) { }
///
@@ -169,8 +165,7 @@ public BZip2InputStream(Stream input)
///
///
public BZip2InputStream(Stream input, bool leaveOpen)
- : base()
- {
+ : base() {
this.input = input;
this._leaveOpen = leaveOpen;
@@ -198,8 +193,7 @@ public BZip2InputStream(Stream input, bool leaveOpen)
/// the offset within that data array to put the first byte read.
/// the number of bytes to read.
/// the number of bytes actually read
- public override int Read(byte[] buffer, int offset, int count)
- {
+ public override int Read(byte[] buffer, int offset, int count) {
if (offset < 0)
throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset));
@@ -216,25 +210,22 @@ public override int Read(byte[] buffer, int offset, int count)
int hi = offset + count;
int destOffset = offset;
- for (int b; (destOffset < hi) && ((b = ReadByte()) >= 0);)
- {
- buffer[destOffset++] = (byte) b;
+ for (int b; (destOffset < hi) && ((b = ReadByte()) >= 0);) {
+ buffer[destOffset++] = (byte)b;
}
return destOffset - offset;
}
- private void MakeMaps()
- {
+ private void MakeMaps() {
bool[] inUse = this.data.inUse;
byte[] seqToUnseq = this.data.seqToUnseq;
int n = 0;
- for (int i = 0; i < 256; i++)
- {
+ for (int i = 0; i < 256; i++) {
if (inUse[i])
- seqToUnseq[n++] = (byte) i;
+ seqToUnseq[n++] = (byte)i;
}
this.nInUse = n;
@@ -244,12 +235,10 @@ private void MakeMaps()
/// Read a single byte from the stream.
///
/// the byte read from the stream, or -1 if EOF
- public override int ReadByte()
- {
+ public override int ReadByte() {
int retChar = this.currentChar;
totalBytesRead++;
- switch (this.currentState)
- {
+ switch (this.currentState) {
case CState.EOF:
return -1;
@@ -294,10 +283,8 @@ public override int ReadByte()
///
/// The return value depends on whether the captive stream supports reading.
///
- public override bool CanRead
- {
- get
- {
+ public override bool CanRead {
+ get {
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
return this.input.CanRead;
}
@@ -310,8 +297,7 @@ public override bool CanRead
///
/// Always returns false.
///
- public override bool CanSeek
- {
+ public override bool CanSeek {
get { return false; }
}
@@ -322,10 +308,8 @@ public override bool CanSeek
///
/// The return value depends on whether the captive stream supports writing.
///
- public override bool CanWrite
- {
- get
- {
+ public override bool CanWrite {
+ get {
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
return input.CanWrite;
}
@@ -334,8 +318,7 @@ public override bool CanWrite
///
/// Flush the stream.
///
- public override void Flush()
- {
+ public override void Flush() {
if (_disposed) throw new ObjectDisposedException("BZip2Stream");
input.Flush();
}
@@ -343,8 +326,7 @@ public override void Flush()
///
/// Reading this property always throws a .
///
- public override long Length
- {
+ public override long Length {
get { throw new NotImplementedException(); }
}
@@ -357,10 +339,8 @@ public override long Length
/// cref="NotImplementedException"/>. Reading will return the
/// total number of uncompressed bytes read in.
///
- public override long Position
- {
- get
- {
+ public override long Position {
+ get {
return this.totalBytesRead;
}
set { throw new NotImplementedException(); }
@@ -372,8 +352,7 @@ public override long Position
/// this is irrelevant, since it will always throw!
/// this is irrelevant, since it will always throw!
/// irrelevant!
- public override long Seek(long offset, System.IO.SeekOrigin origin)
- {
+ public override long Seek(long offset, System.IO.SeekOrigin origin) {
throw new NotImplementedException();
}
@@ -381,8 +360,7 @@ public override long Seek(long offset, System.IO.SeekOrigin origin)
/// Calling this method always throws a .
///
/// this is irrelevant, since it will always throw!
- public override void SetLength(long value)
- {
+ public override void SetLength(long value) {
throw new NotImplementedException();
}
@@ -392,8 +370,7 @@ public override void SetLength(long value)
/// this parameter is never used
/// this parameter is never used
/// this parameter is never used
- public override void Write(byte[] buffer, int offset, int count)
- {
+ public override void Write(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
@@ -404,25 +381,19 @@ public override void Write(byte[] buffer, int offset, int count)
///
/// indicates whether the Dispose method was invoked by user code.
///
- protected override void Dispose(bool disposing)
- {
- try
- {
- if (!_disposed)
- {
+ protected override void Dispose(bool disposing) {
+ try {
+ if (!_disposed) {
if (disposing)
input?.Close();
_disposed = true;
}
- }
- finally
- {
+ } finally {
base.Dispose(disposing);
}
}
- private void init()
- {
+ private void init() {
if (null == this.input)
throw new IOException("No input Stream");
@@ -437,7 +408,7 @@ private void init()
if ((blockSize < '1') || (blockSize > '9'))
throw new IOException("Stream is not BZip2 formatted: illegal "
- + "blocksize " + (char) blockSize);
+ + "blocksize " + (char)blockSize);
this.blockSize100k = blockSize - '0';
@@ -445,19 +416,16 @@ private void init()
SetupBlock();
}
- private void CheckMagicChar(char expected, int position)
- {
+ private void CheckMagicChar(char expected, int position) {
int magic = this.input.ReadByte();
- if (magic != (int)expected)
- {
+ if (magic != (int)expected) {
var msg = String.Format("Not a valid BZip2 stream. byte {0}, expected '{1}', got '{2}'",
position, (int)expected, magic);
throw new IOException(msg);
}
}
- private void InitBlock()
- {
+ private void InitBlock() {
char magic0 = bsGetUByte();
char magic1 = bsGetUByte();
char magic2 = bsGetUByte();
@@ -466,24 +434,19 @@ private void InitBlock()
char magic5 = bsGetUByte();
if (magic0 == 0x17 && magic1 == 0x72 && magic2 == 0x45
- && magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90)
- {
+ && magic3 == 0x38 && magic4 == 0x50 && magic5 == 0x90) {
complete(); // end of file
- }
- else if (magic0 != 0x31 ||
- magic1 != 0x41 ||
- magic2 != 0x59 ||
- magic3 != 0x26 ||
- magic4 != 0x53 ||
- magic5 != 0x59)
- {
+ } else if (magic0 != 0x31 ||
+ magic1 != 0x41 ||
+ magic2 != 0x59 ||
+ magic3 != 0x26 ||
+ magic4 != 0x53 ||
+ magic5 != 0x59) {
this.currentState = CState.EOF;
var msg = String.Format("bad block header at offset 0x{0:X}",
this.input.Position);
throw new IOException(msg);
- }
- else
- {
+ } else {
this.storedBlockCRC = bsGetInt();
// Console.WriteLine(" stored block CRC : {0:X8}", this.storedBlockCRC);
@@ -502,13 +465,11 @@ private void InitBlock()
}
- private void EndBlock()
- {
+ private void EndBlock() {
this.computedBlockCRC = (uint)this.crc.Crc32Result;
// A bad CRC is considered a fatal error.
- if (this.storedBlockCRC != this.computedBlockCRC)
- {
+ if (this.storedBlockCRC != this.computedBlockCRC) {
// make next blocks readable without error
// (repair feature, not yet documented, not tested)
// this.computedCombinedCRC = (this.storedCombinedCRC << 1)
@@ -530,14 +491,12 @@ private void EndBlock()
}
- private void complete()
- {
+ private void complete() {
this.storedCombinedCRC = bsGetInt();
this.currentState = CState.EOF;
this.data = null;
- if (this.storedCombinedCRC != this.computedCombinedCRC)
- {
+ if (this.storedCombinedCRC != this.computedCombinedCRC) {
var msg = String.Format("BZip2 CRC error (expected {0:X8}, computed {1:X8})",
this.storedCombinedCRC, this.computedCombinedCRC);
@@ -548,18 +507,13 @@ private void complete()
///
/// Close the stream.
///
- public override void Close()
- {
+ public override void Close() {
Stream inShadow = this.input;
- if (inShadow != null)
- {
- try
- {
+ if (inShadow != null) {
+ try {
if (!this._leaveOpen)
inShadow.Close();
- }
- finally
- {
+ } finally {
this.data = null;
this.input = null;
}
@@ -579,15 +533,12 @@ public override void Close()
///
/// The number of bits to read, always between 1 and 32.
///
- private int GetBits(int n)
- {
+ private int GetBits(int n) {
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
- if (bsLiveShadow < n)
- {
- do
- {
+ if (bsLiveShadow < n) {
+ do {
int thech = this.input.ReadByte();
if (thech < 0)
@@ -630,19 +581,16 @@ private int GetBits(int n)
// return ((bsBuffShadow >> (bsLiveShadow - 1)) & 1) != 0;
// }
- private bool bsGetBit()
- {
+ private bool bsGetBit() {
int bit = GetBits(1);
return bit != 0;
}
- private char bsGetUByte()
- {
- return (char) GetBits(8);
+ private char bsGetUByte() {
+ return (char)GetBits(8);
}
- private uint bsGetInt()
- {
+ private uint bsGetInt() {
return (uint)((((((GetBits(8) << 8) | GetBits(8)) << 8) | GetBits(8)) << 8) | GetBits(8));
}
@@ -651,39 +599,31 @@ private uint bsGetInt()
* Called by createHuffmanDecodingTables() exclusively.
*/
private static void hbCreateDecodeTables(int[] limit,
- int[] bbase, int[] perm, char[] length,
- int minLen, int maxLen, int alphaSize)
- {
- for (int i = minLen, pp = 0; i <= maxLen; i++)
- {
- for (int j = 0; j < alphaSize; j++)
- {
- if (length[j] == i)
- {
+ int[] bbase, int[] perm, char[] length,
+ int minLen, int maxLen, int alphaSize) {
+ for (int i = minLen, pp = 0; i <= maxLen; i++) {
+ for (int j = 0; j < alphaSize; j++) {
+ if (length[j] == i) {
perm[pp++] = j;
}
}
}
- for (int i = BZip2.MaxCodeLength; --i > 0;)
- {
+ for (int i = BZip2.MaxCodeLength; --i > 0;) {
bbase[i] = 0;
limit[i] = 0;
}
- for (int i = 0; i < alphaSize; i++)
- {
+ for (int i = 0; i < alphaSize; i++) {
bbase[length[i] + 1]++;
}
- for (int i = 1, b = bbase[0]; i < BZip2.MaxCodeLength; i++)
- {
+ for (int i = 1, b = bbase[0]; i < BZip2.MaxCodeLength; i++) {
b += bbase[i];
bbase[i] = b;
}
- for (int i = minLen, vec = 0, b = bbase[i]; i <= maxLen; i++)
- {
+ for (int i = minLen, vec = 0, b = bbase[i]; i <= maxLen; i++) {
int nb = bbase[i + 1];
vec += nb - b;
b = nb;
@@ -691,16 +631,14 @@ private static void hbCreateDecodeTables(int[] limit,
vec <<= 1;
}
- for (int i = minLen + 1; i <= maxLen; i++)
- {
+ for (int i = minLen + 1; i <= maxLen; i++) {
bbase[i] = ((limit[i - 1] + 1) << 1) - bbase[i];
}
}
- private void recvDecodingTables()
- {
+ private void recvDecodingTables() {
var s = this.data;
bool[] inUse = s.inUse;
byte[] pos = s.recvDecodingTables_pos;
@@ -709,28 +647,21 @@ private void recvDecodingTables()
int inUse16 = 0;
/* Receive the mapping table */
- for (int i = 0; i < 16; i++)
- {
- if (bsGetBit())
- {
+ for (int i = 0; i < 16; i++) {
+ if (bsGetBit()) {
inUse16 |= 1 << i;
}
}
- for (int i = 256; --i >= 0;)
- {
+ for (int i = 256; --i >= 0;) {
inUse[i] = false;
}
- for (int i = 0; i < 16; i++)
- {
- if ((inUse16 & (1 << i)) != 0)
- {
+ for (int i = 0; i < 16; i++) {
+ if ((inUse16 & (1 << i)) != 0) {
int i16 = i << 4;
- for (int j = 0; j < 16; j++)
- {
- if (bsGetBit())
- {
+ for (int j = 0; j < 16; j++) {
+ if (bsGetBit()) {
inUse[i16 + j] = true;
}
}
@@ -744,28 +675,23 @@ private void recvDecodingTables()
int nGroups = GetBits(3);
int nSelectors = GetBits(15);
- for (int i = 0; i < nSelectors; i++)
- {
+ for (int i = 0; i < nSelectors; i++) {
int j = 0;
- while (bsGetBit())
- {
+ while (bsGetBit()) {
j++;
}
- s.selectorMtf[i] = (byte) j;
+ s.selectorMtf[i] = (byte)j;
}
/* Undo the MTF values for the selectors. */
- for (int v = nGroups; --v >= 0;)
- {
- pos[v] = (byte) v;
+ for (int v = nGroups; --v >= 0;) {
+ pos[v] = (byte)v;
}
- for (int i = 0; i < nSelectors; i++)
- {
+ for (int i = 0; i < nSelectors; i++) {
int v = s.selectorMtf[i];
byte tmp = pos[v];
- while (v > 0)
- {
+ while (v > 0) {
// nearly all times v is zero, 4 in most other cases
pos[v] = pos[v - 1];
v--;
@@ -777,17 +703,14 @@ private void recvDecodingTables()
char[][] len = s.temp_charArray2d;
/* Now the coding tables */
- for (int t = 0; t < nGroups; t++)
- {
+ for (int t = 0; t < nGroups; t++) {
int curr = GetBits(5);
char[] len_t = len[t];
- for (int i = 0; i < alphaSize; i++)
- {
- while (bsGetBit())
- {
+ for (int i = 0; i < alphaSize; i++) {
+ while (bsGetBit()) {
curr += bsGetBit() ? -1 : 1;
}
- len_t[i] = (char) curr;
+ len_t[i] = (char)curr;
}
}
@@ -800,18 +723,15 @@ private void recvDecodingTables()
* Called by recvDecodingTables() exclusively.
*/
private void createHuffmanDecodingTables(int alphaSize,
- int nGroups)
- {
+ int nGroups) {
var s = this.data;
char[][] len = s.temp_charArray2d;
- for (int t = 0; t < nGroups; t++)
- {
+ for (int t = 0; t < nGroups; t++) {
int minLen = 32;
int maxLen = 0;
char[] len_t = len[t];
- for (int i = alphaSize; --i >= 0;)
- {
+ for (int i = alphaSize; --i >= 0;) {
char lent = len_t[i];
if (lent > maxLen)
maxLen = lent;
@@ -827,8 +747,7 @@ private void createHuffmanDecodingTables(int alphaSize,
- private void getAndMoveToFrontDecode()
- {
+ private void getAndMoveToFrontDecode() {
var s = this.data;
this.origPtr = GetBits(24);
@@ -847,9 +766,8 @@ private void getAndMoveToFrontDecode()
* does save having to do it later in a separate pass, and so saves a
* block's worth of cache misses.
*/
- for (int i = 256; --i >= 0;)
- {
- yy[i] = (byte) i;
+ for (int i = 256; --i >= 0;) {
+ yy[i] = (byte)i;
s.unzftab[i] = 0;
}
@@ -866,38 +784,27 @@ private void getAndMoveToFrontDecode()
int[] perm_zt = s.gPerm[zt];
int minLens_zt = s.gMinlen[zt];
- while (nextSym != eob)
- {
- if ((nextSym == BZip2.RUNA) || (nextSym == BZip2.RUNB))
- {
+ while (nextSym != eob) {
+ if ((nextSym == BZip2.RUNA) || (nextSym == BZip2.RUNB)) {
int es = -1;
- for (int n = 1; true; n <<= 1)
- {
- if (nextSym == BZip2.RUNA)
- {
+ for (int n = 1; true; n <<= 1) {
+ if (nextSym == BZip2.RUNA) {
es += n;
- }
- else if (nextSym == BZip2.RUNB)
- {
+ } else if (nextSym == BZip2.RUNB) {
es += n << 1;
- }
- else
- {
+ } else {
break;
}
- if (groupPos == 0)
- {
+ if (groupPos == 0) {
groupPos = BZip2.G_SIZE - 1;
zt = s.selector[++groupNo] & 0xff;
base_zt = s.gBase[zt];
limit_zt = s.gLimit[zt];
perm_zt = s.gPerm[zt];
minLens_zt = s.gMinlen[zt];
- }
- else
- {
+ } else {
groupPos--;
}
@@ -905,17 +812,13 @@ private void getAndMoveToFrontDecode()
// Inlined:
// int zvec = GetBits(zn);
- while (bsLiveShadow < zn)
- {
+ while (bsLiveShadow < zn) {
int thech = this.input.ReadByte();
- if (thech >= 0)
- {
+ if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
- }
- else
- {
+ } else {
throw new IOException("unexpected end of stream");
}
}
@@ -923,20 +826,15 @@ private void getAndMoveToFrontDecode()
& ((1 << zn) - 1);
bsLiveShadow -= zn;
- while (zvec > limit_zt[zn])
- {
+ while (zvec > limit_zt[zn]) {
zn++;
- while (bsLiveShadow < 1)
- {
+ while (bsLiveShadow < 1) {
int thech = this.input.ReadByte();
- if (thech >= 0)
- {
+ if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
- }
- else
- {
+ } else {
throw new IOException("unexpected end of stream");
}
}
@@ -950,16 +848,13 @@ private void getAndMoveToFrontDecode()
byte ch = s.seqToUnseq[yy[0]];
s.unzftab[ch & 0xff] += es + 1;
- while (es-- >= 0)
- {
+ while (es-- >= 0) {
s.ll8[++lastShadow] = ch;
}
if (lastShadow >= limitLast)
throw new IOException("block overrun");
- }
- else
- {
+ } else {
if (++lastShadow >= limitLast)
throw new IOException("block overrun");
@@ -972,31 +867,24 @@ private void getAndMoveToFrontDecode()
* native method call overhead of System.Buffer.BlockCopy for very
* small ranges to copy.
*/
- if (nextSym <= 16)
- {
- for (int j = nextSym - 1; j > 0;)
- {
+ if (nextSym <= 16) {
+ for (int j = nextSym - 1; j > 0;) {
yy[j] = yy[--j];
}
- }
- else
- {
+ } else {
System.Buffer.BlockCopy(yy, 0, yy, 1, nextSym - 1);
}
yy[0] = tmp;
- if (groupPos == 0)
- {
+ if (groupPos == 0) {
groupPos = BZip2.G_SIZE - 1;
zt = s.selector[++groupNo] & 0xff;
base_zt = s.gBase[zt];
limit_zt = s.gLimit[zt];
perm_zt = s.gPerm[zt];
minLens_zt = s.gMinlen[zt];
- }
- else
- {
+ } else {
groupPos--;
}
@@ -1004,17 +892,13 @@ private void getAndMoveToFrontDecode()
// Inlined:
// int zvec = GetBits(zn);
- while (bsLiveShadow < zn)
- {
+ while (bsLiveShadow < zn) {
int thech = this.input.ReadByte();
- if (thech >= 0)
- {
+ if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
- }
- else
- {
+ } else {
throw new IOException("unexpected end of stream");
}
}
@@ -1022,20 +906,15 @@ private void getAndMoveToFrontDecode()
& ((1 << zn) - 1);
bsLiveShadow -= zn;
- while (zvec > limit_zt[zn])
- {
+ while (zvec > limit_zt[zn]) {
zn++;
- while (bsLiveShadow < 1)
- {
+ while (bsLiveShadow < 1) {
int thech = this.input.ReadByte();
- if (thech >= 0)
- {
+ if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
- }
- else
- {
+ } else {
throw new IOException("unexpected end of stream");
}
}
@@ -1052,8 +931,7 @@ private void getAndMoveToFrontDecode()
}
- private int getAndMoveToFrontDecode0(int groupNo)
- {
+ private int getAndMoveToFrontDecode0(int groupNo) {
var s = this.data;
int zt = s.selector[groupNo] & 0xff;
int[] limit_zt = s.gLimit[zt];
@@ -1062,21 +940,16 @@ private int getAndMoveToFrontDecode0(int groupNo)
int bsLiveShadow = this.bsLive;
int bsBuffShadow = this.bsBuff;
- while (zvec > limit_zt[zn])
- {
+ while (zvec > limit_zt[zn]) {
zn++;
- while (bsLiveShadow < 1)
- {
+ while (bsLiveShadow < 1) {
int thech = this.input.ReadByte();
- if (thech >= 0)
- {
+ if (thech >= 0) {
bsBuffShadow = (bsBuffShadow << 8) | thech;
bsLiveShadow += 8;
continue;
- }
- else
- {
+ } else {
throw new IOException("unexpected end of stream");
}
}
@@ -1091,8 +964,7 @@ private int getAndMoveToFrontDecode0(int groupNo)
}
- private void SetupBlock()
- {
+ private void SetupBlock() {
if (this.data == null)
return;
@@ -1103,36 +975,31 @@ private void SetupBlock()
// xxxx
/* Check: unzftab entries in range. */
- for (i = 0; i <= 255; i++)
- {
+ for (i = 0; i <= 255; i++) {
if (s.unzftab[i] < 0 || s.unzftab[i] > this.last)
throw new Exception("BZ_DATA_ERROR");
}
/* Actually generate cftab. */
s.cftab[0] = 0;
- for (i = 1; i <= 256; i++) s.cftab[i] = s.unzftab[i-1];
- for (i = 1; i <= 256; i++) s.cftab[i] += s.cftab[i-1];
+ for (i = 1; i <= 256; i++) s.cftab[i] = s.unzftab[i - 1];
+ for (i = 1; i <= 256; i++) s.cftab[i] += s.cftab[i - 1];
/* Check: cftab entries in range. */
- for (i = 0; i <= 256; i++)
- {
- if (s.cftab[i] < 0 || s.cftab[i] > this.last+1)
- {
+ for (i = 0; i <= 256; i++) {
+ if (s.cftab[i] < 0 || s.cftab[i] > this.last + 1) {
var msg = String.Format("BZ_DATA_ERROR: cftab[{0}]={1} last={2}",
i, s.cftab[i], this.last);
throw new Exception(msg);
}
}
/* Check: cftab entries non-descending. */
- for (i = 1; i <= 256; i++)
- {
- if (s.cftab[i-1] > s.cftab[i])
+ for (i = 1; i <= 256; i++) {
+ if (s.cftab[i - 1] > s.cftab[i])
throw new Exception("BZ_DATA_ERROR");
}
int lastShadow;
- for (i = 0, lastShadow = this.last; i <= lastShadow; i++)
- {
+ for (i = 0, lastShadow = this.last; i <= lastShadow; i++) {
tt[s.cftab[s.ll8[i] & 0xff]++] = i;
}
@@ -1144,37 +1011,28 @@ private void SetupBlock()
this.su_i2 = 0;
this.su_ch2 = 256; /* not a valid 8-bit byte value?, and not EOF */
- if (this.blockRandomised)
- {
+ if (this.blockRandomised) {
this.su_rNToGo = 0;
this.su_rTPos = 0;
SetupRandPartA();
- }
- else
- {
+ } else {
SetupNoRandPartA();
}
}
- private void SetupRandPartA()
- {
- if (this.su_i2 <= this.last)
- {
+ private void SetupRandPartA() {
+ if (this.su_i2 <= this.last) {
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_tPos = this.data.tt[this.su_tPos];
- if (this.su_rNToGo == 0)
- {
+ if (this.su_rNToGo == 0) {
this.su_rNToGo = Rand.Rnums(this.su_rTPos) - 1;
- if (++this.su_rTPos == 512)
- {
+ if (++this.su_rTPos == 512) {
this.su_rTPos = 0;
}
- }
- else
- {
+ } else {
this.su_rNToGo--;
}
this.su_ch2 = su_ch2Shadow ^= (this.su_rNToGo == 1) ? 1 : 0;
@@ -1182,19 +1040,15 @@ private void SetupRandPartA()
this.currentChar = su_ch2Shadow;
this.currentState = CState.RAND_PART_B;
this.crc.UpdateCRC((byte)su_ch2Shadow);
- }
- else
- {
+ } else {
EndBlock();
InitBlock();
SetupBlock();
}
}
- private void SetupNoRandPartA()
- {
- if (this.su_i2 <= this.last)
- {
+ private void SetupNoRandPartA() {
+ if (this.su_i2 <= this.last) {
this.su_chPrev = this.su_ch2;
int su_ch2Shadow = this.data.ll8[this.su_tPos] & 0xff;
this.su_ch2 = su_ch2Shadow;
@@ -1203,9 +1057,7 @@ private void SetupNoRandPartA()
this.currentChar = su_ch2Shadow;
this.currentState = CState.NO_RAND_PART_B;
this.crc.UpdateCRC((byte)su_ch2Shadow);
- }
- else
- {
+ } else {
this.currentState = CState.NO_RAND_PART_A;
EndBlock();
InitBlock();
@@ -1213,55 +1065,40 @@ private void SetupNoRandPartA()
}
}
- private void SetupRandPartB()
- {
- if (this.su_ch2 != this.su_chPrev)
- {
+ private void SetupRandPartB() {
+ if (this.su_ch2 != this.su_chPrev) {
this.currentState = CState.RAND_PART_A;
this.su_count = 1;
SetupRandPartA();
- }
- else if (++this.su_count >= 4)
- {
- this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
+ } else if (++this.su_count >= 4) {
+ this.su_z = (char)(this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
- if (this.su_rNToGo == 0)
- {
+ if (this.su_rNToGo == 0) {
this.su_rNToGo = Rand.Rnums(this.su_rTPos) - 1;
- if (++this.su_rTPos == 512)
- {
+ if (++this.su_rTPos == 512) {
this.su_rTPos = 0;
}
- }
- else
- {
+ } else {
this.su_rNToGo--;
}
this.su_j2 = 0;
this.currentState = CState.RAND_PART_C;
- if (this.su_rNToGo == 1)
- {
+ if (this.su_rNToGo == 1) {
this.su_z ^= (char)1;
}
SetupRandPartC();
- }
- else
- {
+ } else {
this.currentState = CState.RAND_PART_A;
SetupRandPartA();
}
}
- private void SetupRandPartC()
- {
- if (this.su_j2 < this.su_z)
- {
+ private void SetupRandPartC() {
+ if (this.su_j2 < this.su_z) {
this.currentChar = this.su_ch2;
this.crc.UpdateCRC((byte)this.su_ch2);
this.su_j2++;
- }
- else
- {
+ } else {
this.currentState = CState.RAND_PART_A;
this.su_i2++;
this.su_count = 0;
@@ -1269,46 +1106,35 @@ private void SetupRandPartC()
}
}
- private void SetupNoRandPartB()
- {
- if (this.su_ch2 != this.su_chPrev)
- {
+ private void SetupNoRandPartB() {
+ if (this.su_ch2 != this.su_chPrev) {
this.su_count = 1;
SetupNoRandPartA();
- }
- else if (++this.su_count >= 4)
- {
- this.su_z = (char) (this.data.ll8[this.su_tPos] & 0xff);
+ } else if (++this.su_count >= 4) {
+ this.su_z = (char)(this.data.ll8[this.su_tPos] & 0xff);
this.su_tPos = this.data.tt[this.su_tPos];
this.su_j2 = 0;
SetupNoRandPartC();
- }
- else
- {
+ } else {
SetupNoRandPartA();
}
}
- private void SetupNoRandPartC()
- {
- if (this.su_j2 < this.su_z)
- {
+ private void SetupNoRandPartC() {
+ if (this.su_j2 < this.su_z) {
int su_ch2Shadow = this.su_ch2;
this.currentChar = su_ch2Shadow;
this.crc.UpdateCRC((byte)su_ch2Shadow);
this.su_j2++;
this.currentState = CState.NO_RAND_PART_C;
- }
- else
- {
+ } else {
this.su_i2++;
this.su_count = 0;
SetupNoRandPartA();
}
}
- private sealed class DecompressionState
- {
+ private sealed class DecompressionState {
// (with blockSize 900k)
public readonly bool[] inUse = new bool[256];
public readonly byte[] seqToUnseq = new byte[256]; // 256 byte
@@ -1339,18 +1165,17 @@ private sealed class DecompressionState
// 4560782 byte
// ===============
- public DecompressionState(int blockSize100k)
- {
+ public DecompressionState(int blockSize100k) {
this.unzftab = new int[256]; // 1024 byte
- this.gLimit = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
- this.gBase = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
- this.gPerm = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
+ this.gLimit = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
+ this.gBase = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
+ this.gPerm = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
this.gMinlen = new int[BZip2.NGroups]; // 24 byte
this.cftab = new int[257]; // 1028 byte
this.getAndMoveToFrontDecode_yy = new byte[256]; // 512 byte
- this.temp_charArray2d = BZip2.InitRectangularArray(BZip2.NGroups,BZip2.MaxAlphaSize);
+ this.temp_charArray2d = BZip2.InitRectangularArray(BZip2.NGroups, BZip2.MaxAlphaSize);
this.recvDecodingTables_pos = new byte[BZip2.NGroups]; // 6 byte
this.ll8 = new byte[blockSize100k * BZip2.BlockSizeMultiple];
@@ -1363,16 +1188,14 @@ public DecompressionState(int blockSize100k)
* I don't initialize it at construction time to avoid unneccessary
* memory allocation when compressing small files.
*/
- public int[] initTT(int length)
- {
+ public int[] initTT(int length) {
int[] ttShadow = this.tt;
// tt.length should always be >= length, but theoretically
// it can happen, if the compressor mixed small and large
// blocks. Normally only the last block will be smaller
// than others.
- if ((ttShadow == null) || (ttShadow.Length < length))
- {
+ if ((ttShadow == null) || (ttShadow.Length < length)) {
this.tt = ttShadow = new int[length];
}
@@ -1515,36 +1338,33 @@ private struct StateDump {
// }
- internal static class BZip2
- {
- internal static T[][] InitRectangularArray(int d1, int d2)
- {
- var x = new T[d1][];
- for (int i=0; i < d1; i++)
- {
- x[i] = new T[d2];
- }
- return x;
+ internal static class BZip2 {
+ internal static T[][] InitRectangularArray(int d1, int d2) {
+ var x = new T[d1][];
+ for (int i = 0; i < d1; i++) {
+ x[i] = new T[d2];
}
+ return x;
+ }
- public static readonly int BlockSizeMultiple = 100000;
- public static readonly int MinBlockSize = 1;
- public static readonly int MaxBlockSize = 9;
- public static readonly int MaxAlphaSize = 258;
- public static readonly int MaxCodeLength = 23;
- public static readonly char RUNA = (char) 0;
- public static readonly char RUNB = (char) 1;
- public static readonly int NGroups = 6;
- public static readonly int G_SIZE = 50;
- public static readonly int N_ITERS = 4;
- public static readonly int MaxSelectors = (2 + (900000 / G_SIZE));
+ public static readonly int BlockSizeMultiple = 100000;
+ public static readonly int MinBlockSize = 1;
+ public static readonly int MaxBlockSize = 9;
+ public static readonly int MaxAlphaSize = 258;
+ public static readonly int MaxCodeLength = 23;
+ public static readonly char RUNA = (char)0;
+ public static readonly char RUNB = (char)1;
+ public static readonly int NGroups = 6;
+ public static readonly int G_SIZE = 50;
+ public static readonly int N_ITERS = 4;
+ public static readonly int MaxSelectors = (2 + (900000 / G_SIZE));
public static readonly int NUM_OVERSHOOT_BYTES = 20;
- /*
- *
If you are ever unlucky/improbable enough to get a stack
- * overflow whilst sorting, increase the following constant and
- * try again. In practice I have never seen the stack go above 27
- * elems, so the following limit seems very generous.
- */
+ /*
+ *
If you are ever unlucky/improbable enough to get a stack
+ * overflow whilst sorting, increase the following constant and
+ * try again. In practice I have never seen the stack go above 27
+ * elems, so the following limit seems very generous.
+ */
internal static readonly int QSORT_STACK_SIZE = 1000;
diff --git a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2OutputStream.cs b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2OutputStream.cs
index 41863ffb0..95b5d3a80 100644
--- a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2OutputStream.cs
+++ b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BZip2OutputStream.cs
@@ -83,14 +83,12 @@
using System.IO;
-namespace Ionic.BZip2
-{
+namespace Ionic.BZip2 {
///
/// A write-only decorator stream that compresses data as it is
/// written using the BZip2 algorithm.
///
- public class BZip2OutputStream : System.IO.Stream
- {
+ public class BZip2OutputStream : System.IO.Stream {
private int totalBytesWrittenIn;
private bool leaveOpen;
private BZip2Compressor compressor;
@@ -136,8 +134,7 @@ public class BZip2OutputStream : System.IO.Stream
///
///
public BZip2OutputStream(Stream output)
- : this(output, BZip2.MaxBlockSize, false)
- {
+ : this(output, BZip2.MaxBlockSize, false) {
}
@@ -150,8 +147,7 @@ public BZip2OutputStream(Stream output)
/// The valid range is 1..9.
///
public BZip2OutputStream(Stream output, int blockSize)
- : this(output, blockSize, false)
- {
+ : this(output, blockSize, false) {
}
@@ -163,8 +159,7 @@ public BZip2OutputStream(Stream output, int blockSize)
/// whether to leave the captive stream open upon closing this stream.
///
public BZip2OutputStream(Stream output, bool leaveOpen)
- : this(output, BZip2.MaxBlockSize, leaveOpen)
- {
+ : this(output, BZip2.MaxBlockSize, leaveOpen) {
}
@@ -181,11 +176,9 @@ public BZip2OutputStream(Stream output, bool leaveOpen)
///
/// whether to leave the captive stream open upon closing this stream.
///
- public BZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
- {
+ public BZip2OutputStream(Stream output, int blockSize, bool leaveOpen) {
if (blockSize < BZip2.MinBlockSize ||
- blockSize > BZip2.MaxBlockSize)
- {
+ blockSize > BZip2.MaxBlockSize) {
var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}",
blockSize,
BZip2.MinBlockSize, BZip2.MaxBlockSize);
@@ -216,10 +209,8 @@ public BZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
/// constructors that accept a bool value.
///
///
- public override void Close()
- {
- if (output != null)
- {
+ public override void Close() {
+ if (output != null) {
Stream o = this.output;
Finish();
if (!leaveOpen)
@@ -231,17 +222,14 @@ public override void Close()
///
/// Flush the stream.
///
- public override void Flush()
- {
- if (this.output != null)
- {
+ public override void Flush() {
+ if (this.output != null) {
this.bw.Flush();
this.output.Flush();
}
}
- private void EmitHeader()
- {
+ private void EmitHeader() {
var magic = new byte[] {
(byte) 'B',
(byte) 'Z',
@@ -253,8 +241,7 @@ private void EmitHeader()
this.output.Write(magic, 0, magic.Length);
}
- private void EmitTrailer()
- {
+ private void EmitTrailer() {
// A magic 48-bit number, 0x177245385090, to indicate the end
// of the last block. (sqrt(pi), if you want to know)
@@ -277,30 +264,26 @@ private void EmitTrailer()
this.bw.TotalBytesWrittenOut);
}
- private void Finish()
- {
+ private void Finish() {
// Console.WriteLine("BZip2:Finish");
- try
- {
+ try {
var totalBefore = this.bw.TotalBytesWrittenOut;
this.compressor.CompressAndWrite();
- TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})",
+ TraceOutput(TraceBits.Write, "out block length (bytes): {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut - totalBefore);
TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
- this.combinedCRC ^= (uint) compressor.Crc32;
+ this.combinedCRC ^= (uint)compressor.Crc32;
TraceOutput(TraceBits.Crc, " block CRC : {0:X8}",
this.compressor.Crc32);
TraceOutput(TraceBits.Crc, " combined CRC (final) : {0:X8}",
this.combinedCRC);
EmitTrailer();
- }
- finally
- {
+ } finally {
this.output = null;
this.compressor = null;
this.bw = null;
@@ -311,8 +294,7 @@ private void Finish()
///
/// The blocksize parameter specified at construction time.
///
- public int BlockSize
- {
+ public int BlockSize {
get { return this.blockSize100k; }
}
@@ -339,8 +321,7 @@ public int BlockSize
/// The buffer holding data to write to the stream.
/// the offset within that data array to find the first byte to write.
/// the number of bytes to write.
- public override void Write(byte[] buffer, int offset, int count)
- {
+ public override void Write(byte[] buffer, int offset, int count) {
if (offset < 0)
throw new IndexOutOfRangeException(String.Format("offset ({0}) must be > 0", offset));
if (count < 0)
@@ -356,30 +337,28 @@ public override void Write(byte[] buffer, int offset, int count)
int bytesWritten = 0;
int bytesRemaining = count;
- do
- {
+ do {
int n = compressor.Fill(buffer, offset, bytesRemaining);
- if (n != bytesRemaining)
- {
+ if (n != bytesRemaining) {
// The compressor data block is full. Compress and
// write out the compressed data, then reset the
// compressor and continue.
var totalBefore = this.bw.TotalBytesWrittenOut;
this.compressor.CompressAndWrite();
- TraceOutput(TraceBits.Write,"out block length (bytes): {0} (0x{0:X})",
+ TraceOutput(TraceBits.Write, "out block length (bytes): {0} (0x{0:X})",
this.bw.TotalBytesWrittenOut - totalBefore);
- // and now any remaining bits
- TraceOutput(TraceBits.Write,
- " remaining: {0} 0x{1:X}",
- this.bw.NumRemainingBits,
- this.bw.RemainingBits);
+ // and now any remaining bits
+ TraceOutput(TraceBits.Write,
+ " remaining: {0} 0x{1:X}",
+ this.bw.NumRemainingBits,
+ this.bw.RemainingBits);
TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
- this.combinedCRC ^= (uint) compressor.Crc32;
+ this.combinedCRC ^= (uint)compressor.Crc32;
TraceOutput(TraceBits.Crc, " block CRC : {0:X8}",
compressor.Crc32);
TraceOutput(TraceBits.Crc, " combined CRC (after) : {0:X8}",
@@ -402,8 +381,7 @@ public override void Write(byte[] buffer, int offset, int count)
///
/// The return value is always false.
///
- public override bool CanRead
- {
+ public override bool CanRead {
get { return false; }
}
@@ -413,8 +391,7 @@ public override bool CanRead
///
/// Always returns false.
///
- public override bool CanSeek
- {
+ public override bool CanSeek {
get { return false; }
}
@@ -425,10 +402,8 @@ public override bool CanSeek
/// The return value should always be true, unless and until the
/// object is disposed and closed.
///
- public override bool CanWrite
- {
- get
- {
+ public override bool CanWrite {
+ get {
if (this.output == null) throw new ObjectDisposedException("BZip2Stream");
return this.output.CanWrite;
}
@@ -437,8 +412,7 @@ public override bool CanWrite
///
/// Reading this property always throws a .
///
- public override long Length
- {
+ public override long Length {
get { throw new NotImplementedException(); }
}
@@ -451,10 +425,8 @@ public override long Length
/// cref="NotImplementedException"/>. Reading will return the
/// total number of uncompressed bytes written through.
///
- public override long Position
- {
- get
- {
+ public override long Position {
+ get {
return this.totalBytesWrittenIn;
}
set { throw new NotImplementedException(); }
@@ -466,8 +438,7 @@ public override long Position
/// this is irrelevant, since it will always throw!
/// this is irrelevant, since it will always throw!
/// irrelevant!
- public override long Seek(long offset, System.IO.SeekOrigin origin)
- {
+ public override long Seek(long offset, System.IO.SeekOrigin origin) {
throw new NotImplementedException();
}
@@ -475,8 +446,7 @@ public override long Seek(long offset, System.IO.SeekOrigin origin)
/// Calling this method always throws a .
///
/// this is irrelevant, since it will always throw!
- public override void SetLength(long value)
- {
+ public override void SetLength(long value) {
throw new NotImplementedException();
}
@@ -487,32 +457,28 @@ public override void SetLength(long value)
/// this parameter is never used
/// this parameter is never used
/// never returns anything; always throws
- public override int Read(byte[] buffer, int offset, int count)
- {
+ public override int Read(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
// used only when Trace is defined
[Flags]
- private enum TraceBits : uint
- {
- None = 0,
- Crc = 1,
- Write = 2,
- All = 0xffffffff,
+ private enum TraceBits : uint {
+ None = 0,
+ Crc = 1,
+ Write = 2,
+ All = 0xffffffff,
}
[System.Diagnostics.ConditionalAttribute("Trace")]
- private void TraceOutput(TraceBits bits, string format, params object[] varParams)
- {
- if ((bits & this.desiredTrace) != 0)
- {
+ private void TraceOutput(TraceBits bits, string format, params object[] varParams) {
+ if ((bits & this.desiredTrace) != 0) {
//lock(outputLock)
{
int tid = System.Threading.Thread.CurrentThread.GetHashCode();
- Console.ForegroundColor = (ConsoleColor) (tid % 8 + 10);
+ Console.ForegroundColor = (ConsoleColor)(tid % 8 + 10);
Console.Write("{0:000} PBOS ", tid);
Console.WriteLine(format, varParams);
Console.ResetColor();
diff --git a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BitWriter.cs b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BitWriter.cs
index 02ab1bb9a..ab991203f 100644
--- a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BitWriter.cs
+++ b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/BitWriter.cs
@@ -80,21 +80,17 @@
//
-using System;
using System.IO;
-namespace Ionic.BZip2
-{
+namespace Ionic.BZip2 {
- internal class BitWriter
- {
+ internal class BitWriter {
private uint accumulator;
private int nAccumulatedBits;
private Stream output;
private int totalBytesWrittenOut;
- public BitWriter(Stream s)
- {
+ public BitWriter(Stream s) {
this.output = s;
}
@@ -107,26 +103,20 @@ public BitWriter(Stream s)
/// in other words it is valid only after a call to Flush().
///
///
- public byte RemainingBits
- {
- get
- {
- return (byte) (this.accumulator >> (32 - this.nAccumulatedBits) & 0xff);
+ public byte RemainingBits {
+ get {
+ return (byte)(this.accumulator >> (32 - this.nAccumulatedBits) & 0xff);
}
}
- public int NumRemainingBits
- {
- get
- {
+ public int NumRemainingBits {
+ get {
return this.nAccumulatedBits;
}
}
- public int TotalBytesWrittenOut
- {
- get
- {
+ public int TotalBytesWrittenOut {
+ get {
return this.totalBytesWrittenOut;
}
}
@@ -141,8 +131,7 @@ public int TotalBytesWrittenOut
/// distinct data blocks.
///
///
- public void Reset()
- {
+ public void Reset() {
this.accumulator = 0;
this.nAccumulatedBits = 0;
this.totalBytesWrittenOut = 0;
@@ -159,14 +148,12 @@ public void Reset()
/// reasons, this method does not check!
///
///
- public void WriteBits(int nbits, uint value)
- {
+ public void WriteBits(int nbits, uint value) {
int nAccumulated = this.nAccumulatedBits;
uint u = this.accumulator;
- while (nAccumulated >= 8)
- {
- this.output.WriteByte ((byte)(u >> 24 & 0xff));
+ while (nAccumulated >= 8) {
+ this.output.WriteByte((byte)(u >> 24 & 0xff));
this.totalBytesWrittenOut++;
u <<= 8;
nAccumulated -= 8;
@@ -187,16 +174,14 @@ public void WriteBits(int nbits, uint value)
///
/// Write a full 8-bit byte into the output.
///
- public void WriteByte(byte b)
- {
+ public void WriteByte(byte b) {
WriteBits(8, b);
}
///
/// Write four 8-bit bytes into the output.
///
- public void WriteInt(uint u)
- {
+ public void WriteInt(uint u) {
WriteBits(8, (u >> 24) & 0xff);
WriteBits(8, (u >> 16) & 0xff);
WriteBits(8, (u >> 8) & 0xff);
@@ -220,9 +205,8 @@ public void WriteInt(uint u)
/// parent BZip2OutputStream.
///
///
- public void Flush()
- {
- WriteBits(0,0);
+ public void Flush() {
+ WriteBits(0, 0);
}
@@ -231,12 +215,10 @@ public void Flush()
/// necessary. This must be the last method invoked on an instance of
/// BitWriter.
///
- public void FinishAndPad()
- {
+ public void FinishAndPad() {
Flush();
- if (this.NumRemainingBits > 0)
- {
+ if (this.NumRemainingBits > 0) {
byte b = (byte)((this.accumulator >> 24) & 0xff);
this.output.WriteByte(b);
this.totalBytesWrittenOut++;
diff --git a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/CRC32.cs b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/CRC32.cs
index 46f3ad2e4..ffc0397cb 100644
--- a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/CRC32.cs
+++ b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/CRC32.cs
@@ -27,10 +27,8 @@
using System;
-using Interop = System.Runtime.InteropServices;
-namespace Ionic.Crc
-{
+namespace Ionic.Crc {
///
/// Computes a CRC-32. The CRC-32 algorithm is parameterized - you
/// can set the polynomial and enable or disable bit
@@ -42,15 +40,12 @@ namespace Ionic.Crc
/// archive files.
///
- public class CRC32
- {
+ public class CRC32 {
///
/// Indicates the total number of bytes applied to the CRC.
///
- public Int64 TotalBytesRead
- {
- get
- {
+ public Int64 TotalBytesRead {
+ get {
return _TotalBytesRead;
}
}
@@ -58,10 +53,8 @@ public Int64 TotalBytesRead
///
/// Indicates the current CRC for all blocks slurped in.
///
- public Int32 Crc32Result
- {
- get
- {
+ public Int32 Crc32Result {
+ get {
return unchecked((Int32)(~_register));
}
}
@@ -71,8 +64,7 @@ public Int32 Crc32Result
///
/// The stream over which to calculate the CRC32
/// the CRC32 calculation
- public Int32 GetCrc32(System.IO.Stream input)
- {
+ public Int32 GetCrc32(System.IO.Stream input) {
return GetCrc32AndCopy(input, null);
}
@@ -83,13 +75,11 @@ public Int32 GetCrc32(System.IO.Stream input)
/// The stream over which to calculate the CRC32
/// The stream into which to deflate the input
/// the CRC32 calculation
- public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
- {
+ public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output) {
if (input == null)
throw new Exception("The input stream must not be null.");
- unchecked
- {
+ unchecked {
byte[] buffer = new byte[BUFFER_SIZE];
int readSize = BUFFER_SIZE;
@@ -97,8 +87,7 @@ public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
int count = input.Read(buffer, 0, readSize);
output?.Write(buffer, 0, count);
_TotalBytesRead += count;
- while (count > 0)
- {
+ while (count > 0) {
SlurpBlock(buffer, 0, count);
count = input.Read(buffer, 0, readSize);
if (output != null) output.Write(buffer, 0, count);
@@ -117,13 +106,11 @@ public Int32 GetCrc32AndCopy(System.IO.Stream input, System.IO.Stream output)
/// The word to start with.
/// The byte to combine it with.
/// The CRC-ized result.
- public Int32 ComputeCrc32(Int32 W, byte B)
- {
+ public Int32 ComputeCrc32(Int32 W, byte B) {
return _InternalComputeCrc32((UInt32)W, B);
}
- internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
- {
+ internal Int32 _InternalComputeCrc32(UInt32 W, byte B) {
return (Int32)(crc32Table[(W ^ B) & 0xFF] ^ (W >> 8));
}
@@ -135,23 +122,18 @@ internal Int32 _InternalComputeCrc32(UInt32 W, byte B)
/// block of bytes to slurp
/// starting point in the block
/// how many bytes within the block to slurp
- public void SlurpBlock(byte[] block, int offset, int count)
- {
+ public void SlurpBlock(byte[] block, int offset, int count) {
if (block == null)
throw new Exception("The data buffer must not be null.");
// bzip algorithm
- for (int i = 0; i < count; i++)
- {
+ for (int i = 0; i < count; i++) {
int x = offset + i;
byte b = block[x];
- if (this.reverseBits)
- {
+ if (this.reverseBits) {
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
- }
- else
- {
+ } else {
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
@@ -164,15 +146,11 @@ public void SlurpBlock(byte[] block, int offset, int count)
/// Process one byte in the CRC.
///
/// the byte to include into the CRC .
- public void UpdateCRC(byte b)
- {
- if (this.reverseBits)
- {
+ public void UpdateCRC(byte b) {
+ if (this.reverseBits) {
UInt32 temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[temp];
- }
- else
- {
+ } else {
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[temp];
}
@@ -192,19 +170,14 @@ public void UpdateCRC(byte b)
///
/// the byte to include into the CRC.
/// the number of times that byte should be repeated.
- public void UpdateCRC(byte b, int n)
- {
- while (n-- > 0)
- {
- if (this.reverseBits)
- {
+ public void UpdateCRC(byte b, int n) {
+ while (n-- > 0) {
+ if (this.reverseBits) {
uint temp = (_register >> 24) ^ b;
_register = (_register << 8) ^ crc32Table[(temp >= 0)
? temp
: (temp + 256)];
- }
- else
- {
+ } else {
UInt32 temp = (_register & 0x000000FF) ^ b;
_register = (_register >> 8) ^ crc32Table[(temp >= 0)
? temp
@@ -216,10 +189,8 @@ public void UpdateCRC(byte b, int n)
- private static uint ReverseBits(uint data)
- {
- unchecked
- {
+ private static uint ReverseBits(uint data) {
+ unchecked {
uint ret = data;
ret = (ret & 0x55555555) << 1 | (ret >> 1) & 0x55555555;
ret = (ret & 0x33333333) << 2 | (ret >> 2) & 0x33333333;
@@ -229,10 +200,8 @@ private static uint ReverseBits(uint data)
}
}
- private static byte ReverseBits(byte data)
- {
- unchecked
- {
+ private static byte ReverseBits(byte data) {
+ unchecked {
uint u = (uint)data * 0x00020202;
uint m = 0x01044010;
uint s = u & m;
@@ -243,37 +212,27 @@ private static byte ReverseBits(byte data)
- private void GenerateLookupTable()
- {
+ private void GenerateLookupTable() {
crc32Table = new UInt32[256];
- unchecked
- {
+ unchecked {
UInt32 dwCrc;
byte i = 0;
- do
- {
+ do {
dwCrc = i;
- for (byte j = 8; j > 0; j--)
- {
- if ((dwCrc & 1) == 1)
- {
+ for (byte j = 8; j > 0; j--) {
+ if ((dwCrc & 1) == 1) {
dwCrc = (dwCrc >> 1) ^ dwPolynomial;
- }
- else
- {
+ } else {
dwCrc >>= 1;
}
}
- if (reverseBits)
- {
+ if (reverseBits) {
crc32Table[ReverseBits(i)] = ReverseBits(dwCrc);
- }
- else
- {
+ } else {
crc32Table[i] = dwCrc;
}
i++;
- } while (i!=0);
+ } while (i != 0);
}
#if VERBOSE
@@ -294,13 +253,11 @@ private void GenerateLookupTable()
}
- private uint gf2_matrix_times(uint[] matrix, uint vec)
- {
+ private uint gf2_matrix_times(uint[] matrix, uint vec) {
uint sum = 0;
- int i=0;
- while (vec != 0)
- {
- if ((vec & 0x01)== 0x01)
+ int i = 0;
+ while (vec != 0) {
+ if ((vec & 0x01) == 0x01)
sum ^= matrix[i];
vec >>= 1;
i++;
@@ -308,8 +265,7 @@ private uint gf2_matrix_times(uint[] matrix, uint vec)
return sum;
}
- private void gf2_matrix_square(uint[] square, uint[] mat)
- {
+ private void gf2_matrix_square(uint[] square, uint[] mat) {
for (int i = 0; i < 32; i++)
square[i] = gf2_matrix_times(mat, mat[i]);
}
@@ -327,22 +283,20 @@ private void gf2_matrix_square(uint[] square, uint[] mat)
///
/// the crc value to be combined with this one
/// the length of data the CRC value was calculated on
- public void Combine(int crc, int length)
- {
+ public void Combine(int crc, int length) {
uint[] even = new uint[32]; // even-power-of-two zeros operator
uint[] odd = new uint[32]; // odd-power-of-two zeros operator
if (length == 0)
return;
- uint crc1= ~_register;
- uint crc2= (uint) crc;
+ uint crc1 = ~_register;
+ uint crc2 = (uint)crc;
// put operator for one zero bit in odd
odd[0] = this.dwPolynomial; // the CRC-32 polynomial
uint row = 1;
- for (int i = 1; i < 32; i++)
- {
+ for (int i = 1; i < 32; i++) {
odd[i] = row;
row <<= 1;
}
@@ -353,7 +307,7 @@ public void Combine(int crc, int length)
// put operator for four zero bits in odd
gf2_matrix_square(odd, even);
- uint len2 = (uint) length;
+ uint len2 = (uint)length;
// apply len2 zeros to crc1 (first square will put the operator for one
// zero byte, eight zero bits, in even)
@@ -361,7 +315,7 @@ public void Combine(int crc, int length)
// apply zeros operator for this bit of len2
gf2_matrix_square(even, odd);
- if ((len2 & 1)== 1)
+ if ((len2 & 1) == 1)
crc1 = gf2_matrix_times(even, crc1);
len2 >>= 1;
@@ -370,7 +324,7 @@ public void Combine(int crc, int length)
// another iteration of the loop with odd and even swapped
gf2_matrix_square(odd, even);
- if ((len2 & 1)==1)
+ if ((len2 & 1) == 1)
crc1 = gf2_matrix_times(odd, crc1);
len2 >>= 1;
@@ -379,7 +333,7 @@ public void Combine(int crc, int length)
crc1 ^= crc2;
- _register= ~crc1;
+ _register = ~crc1;
//return (int) crc1;
return;
@@ -390,8 +344,7 @@ public void Combine(int crc, int length)
/// Create an instance of the CRC32 class using the default settings: no
/// bit reversal, and a polynomial of 0xEDB88320.
///
- public CRC32() : this(false)
- {
+ public CRC32() : this(false) {
}
///
@@ -411,8 +364,7 @@ public CRC32() : this(false)
///
///
public CRC32(bool reverseBits) :
- this( unchecked((int)0xEDB88320), reverseBits)
- {
+ this(unchecked((int)0xEDB88320), reverseBits) {
}
@@ -441,10 +393,9 @@ public CRC32(bool reverseBits) :
/// reverseBits parameter.
///
///
- public CRC32(int polynomial, bool reverseBits)
- {
+ public CRC32(int polynomial, bool reverseBits) {
this.reverseBits = reverseBits;
- this.dwPolynomial = (uint) polynomial;
+ this.dwPolynomial = (uint)polynomial;
this.GenerateLookupTable();
}
@@ -457,8 +408,7 @@ public CRC32(int polynomial, bool reverseBits)
/// multiple, distinct CRCs on multiple, distinct data blocks.
///
///
- public void Reset()
- {
+ public void Reset() {
_register = 0xFFFFFFFFU;
}
@@ -491,8 +441,7 @@ public void Reset()
/// DotNetZip library.
///
///
- public class CrcCalculatorStream : System.IO.Stream, System.IDisposable
- {
+ public class CrcCalculatorStream : System.IO.Stream, System.IDisposable {
private static readonly Int64 UnsetLengthLimit = -99;
internal System.IO.Stream _innerStream;
@@ -512,8 +461,7 @@ public class CrcCalculatorStream : System.IO.Stream, System.IDisposable
///
/// The underlying stream
public CrcCalculatorStream(System.IO.Stream stream)
- : this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null)
- {
+ : this(true, CrcCalculatorStream.UnsetLengthLimit, stream, null) {
}
///
@@ -530,8 +478,7 @@ public CrcCalculatorStream(System.IO.Stream stream)
/// true to leave the underlying stream
/// open upon close of the CrcCalculatorStream; false otherwise.
public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
- : this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null)
- {
+ : this(leaveOpen, CrcCalculatorStream.UnsetLengthLimit, stream, null) {
}
///
@@ -551,8 +498,7 @@ public CrcCalculatorStream(System.IO.Stream stream, bool leaveOpen)
/// The underlying stream
/// The length of the stream to slurp
public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
- : this(true, length, stream, null)
- {
+ : this(true, length, stream, null) {
if (length < 0)
throw new ArgumentException("length");
}
@@ -573,8 +519,7 @@ public CrcCalculatorStream(System.IO.Stream stream, Int64 length)
/// true to leave the underlying stream
/// open upon close of the CrcCalculatorStream; false otherwise.
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen)
- : this(leaveOpen, length, stream, null)
- {
+ : this(leaveOpen, length, stream, null) {
if (length < 0)
throw new ArgumentException("length");
}
@@ -597,8 +542,7 @@ public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen
/// the CRC32 instance to use to calculate the CRC32
public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen,
CRC32 crc32)
- : this(leaveOpen, length, stream, crc32)
- {
+ : this(leaveOpen, length, stream, crc32) {
if (length < 0)
throw new ArgumentException("length");
}
@@ -611,8 +555,7 @@ public CrcCalculatorStream(System.IO.Stream stream, Int64 length, bool leaveOpen
// value.
private CrcCalculatorStream
(bool leaveOpen, Int64 length, System.IO.Stream stream, CRC32 crc32)
- : base()
- {
+ : base() {
_innerStream = stream;
_Crc32 = crc32 ?? new CRC32();
_lengthLimit = length;
@@ -628,8 +571,7 @@ private CrcCalculatorStream
/// This is either the total number of bytes read, or the total number of
/// bytes written, depending on the direction of this stream.
///
- public Int64 TotalBytesSlurped
- {
+ public Int64 TotalBytesSlurped {
get { return _Crc32.TotalBytesRead; }
}
@@ -643,8 +585,7 @@ public Int64 TotalBytesSlurped
/// get an accurate CRC for the entire stream.
///
///
- public Int32 Crc
- {
+ public Int32 Crc {
get { return _Crc32.Crc32Result; }
}
@@ -657,8 +598,7 @@ public Int32 Crc
/// Set this at any point before calling .
///
///
- public bool LeaveOpen
- {
+ public bool LeaveOpen {
get { return _leaveOpen; }
set { _leaveOpen = value; }
}
@@ -670,8 +610,7 @@ public bool LeaveOpen
/// the offset at which to start
/// the number of bytes to read
/// the number of bytes actually read
- public override int Read(byte[] buffer, int offset, int count)
- {
+ public override int Read(byte[] buffer, int offset, int count) {
int bytesToRead = count;
// Need to limit the # of bytes returned, if the stream is intended to have
@@ -682,8 +621,7 @@ public override int Read(byte[] buffer, int offset, int count)
// calling ReadToEnd() on it, We can "over-read" the zip data and get a
// corrupt string. The length limits that, prevents that problem.
- if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit)
- {
+ if (_lengthLimit != CrcCalculatorStream.UnsetLengthLimit) {
if (_Crc32.TotalBytesRead >= _lengthLimit) return 0; // EOF
Int64 bytesRemaining = _lengthLimit - _Crc32.TotalBytesRead;
if (bytesRemaining < count) bytesToRead = (int)bytesRemaining;
@@ -699,8 +637,7 @@ public override int Read(byte[] buffer, int offset, int count)
/// the buffer from which to write
/// the offset at which to start writing
/// the number of bytes to write
- public override void Write(byte[] buffer, int offset, int count)
- {
+ public override void Write(byte[] buffer, int offset, int count) {
if (count > 0) _Crc32.SlurpBlock(buffer, offset, count);
_innerStream.Write(buffer, offset, count);
}
@@ -708,8 +645,7 @@ public override void Write(byte[] buffer, int offset, int count)
///
/// Indicates whether the stream supports reading.
///
- public override bool CanRead
- {
+ public override bool CanRead {
get { return _innerStream.CanRead; }
}
@@ -721,34 +657,29 @@ public override bool CanRead
/// Always returns false.
///
///
- public override bool CanSeek
- {
+ public override bool CanSeek {
get { return false; }
}
///
/// Indicates whether the stream supports writing.
///
- public override bool CanWrite
- {
+ public override bool CanWrite {
get { return _innerStream.CanWrite; }
}
///
/// Flush the stream.
///
- public override void Flush()
- {
+ public override void Flush() {
_innerStream.Flush();
}
///
/// Returns the length of the underlying stream.
///
- public override long Length
- {
- get
- {
+ public override long Length {
+ get {
if (_lengthLimit == CrcCalculatorStream.UnsetLengthLimit)
return _innerStream.Length;
else return _lengthLimit;
@@ -760,8 +691,7 @@ public override long Length
/// If you use the setter, it will throw
/// .
///
- public override long Position
- {
+ public override long Position {
get { return _Crc32.TotalBytesRead; }
set { throw new NotSupportedException(); }
}
@@ -773,8 +703,7 @@ public override long Position
/// N/A
/// N/A
/// N/A
- public override long Seek(long offset, System.IO.SeekOrigin origin)
- {
+ public override long Seek(long offset, System.IO.SeekOrigin origin) {
throw new NotSupportedException();
}
@@ -783,22 +712,19 @@ public override long Seek(long offset, System.IO.SeekOrigin origin)
///
///
/// N/A
- public override void SetLength(long value)
- {
+ public override void SetLength(long value) {
throw new NotSupportedException();
}
- void IDisposable.Dispose()
- {
+ void IDisposable.Dispose() {
Close();
}
///
/// Closes the stream.
///
- public override void Close()
- {
+ public override void Close() {
base.Close();
if (!_leaveOpen)
_innerStream.Close();
diff --git a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/ParallelBZip2OutputStream.cs b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/ParallelBZip2OutputStream.cs
index 91193f5aa..3231651f3 100644
--- a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/ParallelBZip2OutputStream.cs
+++ b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/ParallelBZip2OutputStream.cs
@@ -129,22 +129,19 @@
//
using System;
-using System.IO;
using System.Collections.Generic;
+using System.IO;
using System.Threading;
-namespace Ionic.BZip2
-{
- internal class WorkItem
- {
+namespace Ionic.BZip2 {
+ internal class WorkItem {
public int index;
public BZip2Compressor Compressor { get; private set; }
public MemoryStream ms;
public int ordinal;
public BitWriter bw;
- public WorkItem(int ix, int blockSize)
- {
+ public WorkItem(int ix, int blockSize) {
// compressed data gets written to a MemoryStream
this.ms = new MemoryStream();
this.bw = new BitWriter(ms);
@@ -184,8 +181,7 @@ public WorkItem(int ix, int blockSize)
///
///
///
- public class ParallelBZip2OutputStream : System.IO.Stream
- {
+ public class ParallelBZip2OutputStream : System.IO.Stream {
private static readonly int BufferPairsPerCore = 4;
private int _maxWorkers;
private bool firstWriteDone;
@@ -196,8 +192,8 @@ public class ParallelBZip2OutputStream : System.IO.Stream
private volatile Exception pendingException;
private bool handlingException;
private bool emitting;
- private System.Collections.Generic.Queue toWrite;
- private System.Collections.Generic.Queue toFill;
+ private System.Collections.Generic.Queue toWrite;
+ private System.Collections.Generic.Queue toFill;
private System.Collections.Generic.List pool;
private object latestLock = new object();
private object eLock = new object(); // for exceptions
@@ -248,8 +244,7 @@ public class ParallelBZip2OutputStream : System.IO.Stream
///
///
public ParallelBZip2OutputStream(Stream output)
- : this(output, BZip2.MaxBlockSize, false)
- {
+ : this(output, BZip2.MaxBlockSize, false) {
}
///
@@ -261,8 +256,7 @@ public ParallelBZip2OutputStream(Stream output)
/// The valid range is 1..9.
///
public ParallelBZip2OutputStream(Stream output, int blockSize)
- : this(output, blockSize, false)
- {
+ : this(output, blockSize, false) {
}
///
@@ -273,8 +267,7 @@ public ParallelBZip2OutputStream(Stream output, int blockSize)
/// whether to leave the captive stream open upon closing this stream.
///
public ParallelBZip2OutputStream(Stream output, bool leaveOpen)
- : this(output, BZip2.MaxBlockSize, leaveOpen)
- {
+ : this(output, BZip2.MaxBlockSize, leaveOpen) {
}
///
@@ -290,10 +283,8 @@ public ParallelBZip2OutputStream(Stream output, bool leaveOpen)
///
/// whether to leave the captive stream open upon closing this stream.
///
- public ParallelBZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
- {
- if (blockSize < BZip2.MinBlockSize || blockSize > BZip2.MaxBlockSize)
- {
+ public ParallelBZip2OutputStream(Stream output, int blockSize, bool leaveOpen) {
+ if (blockSize < BZip2.MinBlockSize || blockSize > BZip2.MaxBlockSize) {
var msg = String.Format("blockSize={0} is out of range; must be between {1} and {2}",
blockSize,
BZip2.MinBlockSize, BZip2.MaxBlockSize);
@@ -313,15 +304,13 @@ public ParallelBZip2OutputStream(Stream output, int blockSize, bool leaveOpen)
}
- private void InitializePoolOfWorkItems()
- {
+ private void InitializePoolOfWorkItems() {
this.toWrite = new Queue();
this.toFill = new Queue();
this.pool = new System.Collections.Generic.List();
int nWorkers = BufferPairsPerCore * Environment.ProcessorCount;
nWorkers = Math.Min(nWorkers, this.MaxWorkers);
- for(int i=0; i < nWorkers; i++)
- {
+ for (int i = 0; i < nWorkers; i++) {
this.pool.Add(new WorkItem(i, this.blockSize100k));
this.toFill.Enqueue(i);
}
@@ -395,14 +384,11 @@ private void InitializePoolOfWorkItems()
/// allocated.
///
///
- public int MaxWorkers
- {
- get
- {
+ public int MaxWorkers {
+ get {
return _maxWorkers;
}
- set
- {
+ set {
if (value < 4)
throw new ArgumentException("MaxWorkers",
"Value must be 4 or greater.");
@@ -419,10 +405,8 @@ public int MaxWorkers
/// constructors that accept a bool value.
///
///
- public override void Close()
- {
- if (this.pendingException != null)
- {
+ public override void Close() {
+ if (this.pendingException != null) {
this.handlingException = true;
var pe = this.pendingException;
this.pendingException = null;
@@ -437,12 +421,9 @@ public override void Close()
Stream o = this.output;
- try
- {
+ try {
FlushOutput(true);
- }
- finally
- {
+ } finally {
this.output = null;
this.bw = null;
}
@@ -452,25 +433,20 @@ public override void Close()
}
- private void FlushOutput(bool lastInput)
- {
+ private void FlushOutput(bool lastInput) {
if (this.emitting) return;
// compress and write whatever is ready
- if (this.currentlyFilling >= 0)
- {
+ if (this.currentlyFilling >= 0) {
WorkItem workitem = this.pool[this.currentlyFilling];
CompressOne(workitem);
this.currentlyFilling = -1; // get a new buffer next Write()
}
- if (lastInput)
- {
+ if (lastInput) {
EmitPendingBuffers(true, false);
EmitTrailer();
- }
- else
- {
+ } else {
EmitPendingBuffers(false, false);
}
}
@@ -480,18 +456,15 @@ private void FlushOutput(bool lastInput)
///
/// Flush the stream.
///
- public override void Flush()
- {
- if (this.output != null)
- {
+ public override void Flush() {
+ if (this.output != null) {
FlushOutput(false);
this.bw.Flush();
this.output.Flush();
}
}
- private void EmitHeader()
- {
+ private void EmitHeader() {
var magic = new byte[] {
(byte) 'B',
(byte) 'Z',
@@ -503,8 +476,7 @@ private void EmitHeader()
this.output.Write(magic, 0, magic.Length);
}
- private void EmitTrailer()
- {
+ private void EmitTrailer() {
// A magic 48-bit number, 0x177245385090, to indicate the end
// of the last block. (sqrt(pi), if you want to know)
@@ -531,8 +503,7 @@ private void EmitTrailer()
///
/// The blocksize parameter specified at construction time.
///
- public int BlockSize
- {
+ public int BlockSize {
get { return this.blockSize100k; }
}
@@ -561,8 +532,7 @@ public int BlockSize
/// The buffer holding data to write to the stream.
/// the offset within that data array to find the first byte to write.
/// the number of bytes to write.
- public override void Write(byte[] buffer, int offset, int count)
- {
+ public override void Write(byte[] buffer, int offset, int count) {
bool mustWait = false;
// This method does this:
@@ -575,8 +545,7 @@ public override void Write(byte[] buffer, int offset, int count)
throw new IOException("the stream is not open");
// dispense any exceptions that occurred on the BG threads
- if (this.pendingException != null)
- {
+ if (this.pendingException != null) {
this.handlingException = true;
var pe = this.pendingException;
this.pendingException = null;
@@ -595,8 +564,7 @@ public override void Write(byte[] buffer, int offset, int count)
if (count == 0) return; // nothing to do
- if (!this.firstWriteDone)
- {
+ if (!this.firstWriteDone) {
// Want to do this on first Write, first session, and not in the
// constructor. Must allow the MaxWorkers to change after
// construction, but before first Write().
@@ -607,8 +575,7 @@ public override void Write(byte[] buffer, int offset, int count)
int bytesWritten = 0;
int bytesRemaining = count;
- do
- {
+ do {
// may need to make buffers available
EmitPendingBuffers(false, mustWait);
@@ -616,14 +583,10 @@ public override void Write(byte[] buffer, int offset, int count)
// get a compressor to fill
int ix = -1;
- if (this.currentlyFilling >= 0)
- {
+ if (this.currentlyFilling >= 0) {
ix = this.currentlyFilling;
- }
- else
- {
- if (this.toFill.Count == 0)
- {
+ } else {
+ if (this.toFill.Count == 0) {
// No compressors available to fill, so... need to emit
// compressed buffers.
mustWait = true;
@@ -638,15 +601,13 @@ public override void Write(byte[] buffer, int offset, int count)
workitem.ordinal = this.lastFilled;
int n = workitem.Compressor.Fill(buffer, offset, bytesRemaining);
- if (n != bytesRemaining)
- {
- if (!ThreadPool.QueueUserWorkItem( CompressOne, workitem ))
+ if (n != bytesRemaining) {
+ if (!ThreadPool.QueueUserWorkItem(CompressOne, workitem))
throw new Exception("Cannot enqueue workitem");
this.currentlyFilling = -1; // will get a new buffer next time
offset += n;
- }
- else
+ } else
this.currentlyFilling = ix;
bytesRemaining -= n;
@@ -660,8 +621,7 @@ public override void Write(byte[] buffer, int offset, int count)
- private void EmitPendingBuffers(bool doAll, bool mustWait)
- {
+ private void EmitPendingBuffers(bool doAll, bool mustWait) {
// When combining parallel compression with a ZipSegmentedStream, it's
// possible for the ZSS to throw from within this method. In that
// case, Close/Dispose will be called on this stream, if this stream
@@ -676,47 +636,36 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
if (doAll || mustWait)
this.newlyCompressedBlob.WaitOne();
- do
- {
+ do {
int firstSkip = -1;
int millisecondsToWait = doAll ? 200 : (mustWait ? -1 : 0);
int nextToWrite = -1;
- do
- {
- if (Monitor.TryEnter(this.toWrite, millisecondsToWait))
- {
+ do {
+ if (Monitor.TryEnter(this.toWrite, millisecondsToWait)) {
nextToWrite = -1;
- try
- {
+ try {
if (this.toWrite.Count > 0)
nextToWrite = this.toWrite.Dequeue();
- }
- finally
- {
+ } finally {
Monitor.Exit(this.toWrite);
}
- if (nextToWrite >= 0)
- {
+ if (nextToWrite >= 0) {
WorkItem workitem = this.pool[nextToWrite];
- if (workitem.ordinal != this.lastWritten + 1)
- {
+ if (workitem.ordinal != this.lastWritten + 1) {
// out of order. requeue and try again.
- lock(this.toWrite)
- {
+ lock (this.toWrite) {
this.toWrite.Enqueue(nextToWrite);
}
- if (firstSkip == nextToWrite)
- {
+ if (firstSkip == nextToWrite) {
// We went around the list once.
// None of the items in the list is the one we want.
// Now wait for a compressor to signal again.
this.newlyCompressedBlob.WaitOne();
firstSkip = -1;
- }
- else if (firstSkip == -1)
+ } else if (firstSkip == -1)
firstSkip = nextToWrite;
continue;
@@ -731,7 +680,7 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
var bw2 = workitem.bw;
bw2.Flush(); // not bw2.FinishAndPad()!
var ms = workitem.ms;
- ms.Seek(0,SeekOrigin.Begin);
+ ms.Seek(0, SeekOrigin.Begin);
// cannot dump bytes!!
// ms.WriteTo(this.output);
@@ -741,8 +690,7 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
int y = -1;
long totOut = 0;
var buffer = new byte[1024];
- while ((n = ms.Read(buffer,0,buffer.Length)) > 0)
- {
+ while ((n = ms.Read(buffer, 0, buffer.Length)) > 0) {
#if Trace
if (y == -1) // diagnostics only
{
@@ -754,8 +702,7 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
}
#endif
y = n;
- for (int k=0; k < n; k++)
- {
+ for (int k = 0; k < n; k++) {
this.bw.WriteByte(buffer[k]);
}
totOut += n;
@@ -774,15 +721,14 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
" remaining bits: {0} 0x{1:X}",
bw2.NumRemainingBits,
bw2.RemainingBits);
- if (bw2.NumRemainingBits > 0)
- {
+ if (bw2.NumRemainingBits > 0) {
this.bw.WriteBits(bw2.NumRemainingBits, bw2.RemainingBits);
}
- TraceOutput(TraceBits.Crc," combined CRC (before): {0:X8}",
+ TraceOutput(TraceBits.Crc, " combined CRC (before): {0:X8}",
this.combinedCRC);
this.combinedCRC = (this.combinedCRC << 1) | (this.combinedCRC >> 31);
- this.combinedCRC ^= (uint) workitem.Compressor.Crc32;
+ this.combinedCRC ^= (uint)workitem.Compressor.Crc32;
TraceOutput(TraceBits.Crc,
" block CRC : {0:X8}",
@@ -805,16 +751,14 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
// don't wait next time through
if (millisecondsToWait == -1) millisecondsToWait = 0;
}
- }
- else
+ } else
nextToWrite = -1;
} while (nextToWrite >= 0);
} while (doAll && (this.lastWritten != this.latestCompressed));
- if (doAll)
- {
+ if (doAll) {
TraceOutput(TraceBits.Crc,
" combined CRC (final) : {0:X8}", this.combinedCRC);
}
@@ -823,32 +767,25 @@ private void EmitPendingBuffers(bool doAll, bool mustWait)
}
- private void CompressOne(Object wi)
- {
+ private void CompressOne(Object wi) {
// compress and one buffer
- WorkItem workitem = (WorkItem) wi;
- try
- {
+ WorkItem workitem = (WorkItem)wi;
+ try {
// compress and write to the compressor's MemoryStream
workitem.Compressor.CompressAndWrite();
- lock(this.latestLock)
- {
+ lock (this.latestLock) {
if (workitem.ordinal > this.latestCompressed)
this.latestCompressed = workitem.ordinal;
}
- lock (this.toWrite)
- {
+ lock (this.toWrite) {
this.toWrite.Enqueue(workitem.index);
}
this.newlyCompressedBlob.Set();
- }
- catch (System.Exception exc1)
- {
- lock(this.eLock)
- {
+ } catch (System.Exception exc1) {
+ lock (this.eLock) {
// expose the exception to the main thread
- if (this.pendingException!=null)
+ if (this.pendingException != null)
this.pendingException = exc1;
}
}
@@ -863,8 +800,7 @@ private void CompressOne(Object wi)
///
/// The return value is always false.
///
- public override bool CanRead
- {
+ public override bool CanRead {
get { return false; }
}
@@ -874,8 +810,7 @@ public override bool CanRead
///
/// Always returns false.
///
- public override bool CanSeek
- {
+ public override bool CanSeek {
get { return false; }
}
@@ -885,10 +820,8 @@ public override bool CanSeek
///
/// The return value depends on whether the captive stream supports writing.
///
- public override bool CanWrite
- {
- get
- {
+ public override bool CanWrite {
+ get {
if (this.output == null) throw new ObjectDisposedException("BZip2Stream");
return this.output.CanWrite;
}
@@ -897,8 +830,7 @@ public override bool CanWrite
///
/// Reading this property always throws a .
///
- public override long Length
- {
+ public override long Length {
get { throw new NotImplementedException(); }
}
@@ -911,10 +843,8 @@ public override long Length
/// cref="NotImplementedException"/>. Reading will return the
/// total number of uncompressed bytes written through.
///
- public override long Position
- {
- get
- {
+ public override long Position {
+ get {
return this.totalBytesWrittenIn;
}
set { throw new NotImplementedException(); }
@@ -934,8 +864,7 @@ public override long Position
/// this is irrelevant, since it will always throw!
/// this is irrelevant, since it will always throw!
/// irrelevant!
- public override long Seek(long offset, System.IO.SeekOrigin origin)
- {
+ public override long Seek(long offset, System.IO.SeekOrigin origin) {
throw new NotImplementedException();
}
@@ -943,8 +872,7 @@ public override long Seek(long offset, System.IO.SeekOrigin origin)
/// Calling this method always throws a .
///
/// this is irrelevant, since it will always throw!
- public override void SetLength(long value)
- {
+ public override void SetLength(long value) {
throw new NotImplementedException();
}
@@ -955,32 +883,27 @@ public override void SetLength(long value)
/// this parameter is never used
/// this parameter is never used
/// never returns anything; always throws
- public override int Read(byte[] buffer, int offset, int count)
- {
+ public override int Read(byte[] buffer, int offset, int count) {
throw new NotImplementedException();
}
// used only when Trace is defined
[Flags]
- private enum TraceBits : uint
- {
- None = 0,
- Crc = 1,
- Write = 2,
- All = 0xffffffff,
+ private enum TraceBits : uint {
+ None = 0,
+ Crc = 1,
+ Write = 2,
+ All = 0xffffffff,
}
[System.Diagnostics.ConditionalAttribute("Trace")]
- private void TraceOutput(TraceBits bits, string format, params object[] varParams)
- {
- if ((bits & this.desiredTrace) != 0)
- {
- lock(outputLock)
- {
+ private void TraceOutput(TraceBits bits, string format, params object[] varParams) {
+ if ((bits & this.desiredTrace) != 0) {
+ lock (outputLock) {
int tid = Thread.CurrentThread.GetHashCode();
- Console.ForegroundColor = (ConsoleColor) (tid % 8 + 10);
+ Console.ForegroundColor = (ConsoleColor)(tid % 8 + 10);
Console.Write("{0:000} PBOS ", tid);
Console.WriteLine(format, varParams);
Console.ResetColor();
diff --git a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/Rand.cs b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/Rand.cs
index ac00decd2..654ae49da 100644
--- a/Src/IronPython.Modules/bz2/dotnetzip/BZip2/Rand.cs
+++ b/Src/IronPython.Modules/bz2/dotnetzip/BZip2/Rand.cs
@@ -24,10 +24,8 @@
// ------------------------------------------------------------------
-namespace Ionic.BZip2
-{
- internal static class Rand
- {
+namespace Ionic.BZip2 {
+ internal static class Rand {
private static int[] RNUMS =
{
619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
@@ -90,8 +88,7 @@ internal static class Rand
///
/// the index
/// the random number
- internal static int Rnums(int i)
- {
+ internal static int Rnums(int i) {
return RNUMS[i];
}
}
diff --git a/Src/IronPython.Modules/gc.cs b/Src/IronPython.Modules/gc.cs
index 87bcacbaf..a27605892 100644
--- a/Src/IronPython.Modules/gc.cs
+++ b/Src/IronPython.Modules/gc.cs
@@ -5,13 +5,11 @@
using System;
using System.Linq;
-using Microsoft.Scripting;
-using Microsoft.Scripting.Runtime;
-
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
-using IronPython.Runtime.Types;
+
+using Microsoft.Scripting.Runtime;
using SpecialName = System.Runtime.CompilerServices.SpecialNameAttribute;
@@ -29,7 +27,7 @@ public static class PythonGC {
private static readonly object _threadholdKey = new object();
[SpecialName]
- public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
+ public static void PerformModuleReload(PythonContext/*!*/ context, PythonDictionary/*!*/ dict) {
context.SetModuleState(_threadholdKey, PythonTuple.MakeTuple(64 * 1024, 256 * 1024, 1024 * 1024));
}
@@ -65,19 +63,19 @@ public static object[] get_objects() {
}
public static void set_threshold(CodeContext/*!*/ context, params object[] args) {
- if(args.Length == 0) {
+ if (args.Length == 0) {
throw PythonOps.TypeError("set_threshold() takes at least 1 argument (0 given)");
}
- if(args.Length > 3) {
+ if (args.Length > 3) {
throw PythonOps.TypeError("set_threshold() takes at most 3 arguments ({0} given)", args.Length);
}
- if(args.Any(x => x is double)) {
+ if (args.Any(x => x is double)) {
throw PythonOps.TypeError("integer argument expected, got float");
}
- if(!args.All(x => x is int)) {
+ if (!args.All(x => x is int)) {
throw PythonOps.TypeError("an integer is required");
}
diff --git a/Src/IronPython.Modules/grp.cs b/Src/IronPython.Modules/grp.cs
index d46de20f5..16dfe8b26 100644
--- a/Src/IronPython.Modules/grp.cs
+++ b/Src/IronPython.Modules/grp.cs
@@ -8,16 +8,14 @@
using System.Collections.Generic;
using System.Runtime.InteropServices;
-using Microsoft.Scripting.Runtime;
-
using IronPython.Runtime;
using IronPython.Runtime.Operations;
-using System.Numerics;
+using Microsoft.Scripting.Runtime;
[assembly: PythonModule("grp", typeof(IronPython.Modules.PythonGrp), PlatformsAttribute.PlatformFamily.Unix)]
namespace IronPython.Modules {
-
+
public static class PythonGrp {
public const string __doc__ = @"Access to the Unix group database.
@@ -79,13 +77,10 @@ private static struct_group Make(IntPtr pwd) {
return new struct_group(g.gr_name, g.gr_passwd, g.gr_gid, PythonList.FromEnumerable(MarshalStringArray(g.gr_mem)));
}
- private static IEnumerable MarshalStringArray(IntPtr arrayPtr)
- {
- if (arrayPtr != IntPtr.Zero)
- {
+ private static IEnumerable MarshalStringArray(IntPtr arrayPtr) {
+ if (arrayPtr != IntPtr.Zero) {
IntPtr ptr = Marshal.ReadIntPtr(arrayPtr);
- while (ptr != IntPtr.Zero)
- {
+ while (ptr != IntPtr.Zero) {
string key = Marshal.PtrToStringAnsi(ptr);
yield return key;
arrayPtr = new IntPtr(arrayPtr.ToInt64() + IntPtr.Size);
@@ -96,7 +91,7 @@ private static IEnumerable MarshalStringArray(IntPtr arrayPtr)
public static struct_group getgrgid(int gid) {
var grp = _getgrgid(gid);
- if(grp == IntPtr.Zero) {
+ if (grp == IntPtr.Zero) {
throw PythonOps.KeyError($"getgrgid(): gid not found: {gid}");
}
@@ -105,7 +100,7 @@ public static struct_group getgrgid(int gid) {
public static struct_group getgrnam(string name) {
var grp = _getgrnam(name);
- if(grp == IntPtr.Zero) {
+ if (grp == IntPtr.Zero) {
throw PythonOps.KeyError($"getgrnam()): name not found: {name}");
}
@@ -116,27 +111,27 @@ public static PythonList getgrall() {
var res = new PythonList();
setgrent();
IntPtr val = getgrent();
- while(val != IntPtr.Zero) {
+ while (val != IntPtr.Zero) {
res.Add(Make(val));
val = getgrent();
}
-
+
return res;
}
#region P/Invoke Declarations
- [DllImport("libc", EntryPoint="getgrgid", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", EntryPoint = "getgrgid", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _getgrgid(int uid);
- [DllImport("libc", EntryPoint="getgrnam", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", EntryPoint = "getgrnam", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _getgrnam([MarshalAs(UnmanagedType.LPStr)] string name);
- [DllImport("libc", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern void setgrent();
- [DllImport("libc", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr getgrent();
#endregion
diff --git a/Src/IronPython.Modules/hashlib/SHA224Managed.cs b/Src/IronPython.Modules/hashlib/SHA224Managed.cs
index 6037a5df2..4840afd76 100644
--- a/Src/IronPython.Modules/hashlib/SHA224Managed.cs
+++ b/Src/IronPython.Modules/hashlib/SHA224Managed.cs
@@ -29,8 +29,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
-using System.Security.Cryptography;
-
using IronPython.Runtime;
namespace Mono.Security.Cryptography {
diff --git a/Src/IronPython.Modules/hashlib/SHA384Managed.cs b/Src/IronPython.Modules/hashlib/SHA384Managed.cs
index 6ea90617b..e47a86c94 100644
--- a/Src/IronPython.Modules/hashlib/SHA384Managed.cs
+++ b/Src/IronPython.Modules/hashlib/SHA384Managed.cs
@@ -30,7 +30,6 @@
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
-using System;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
diff --git a/Src/IronPython.Modules/hashlib/_hashlib.cs b/Src/IronPython.Modules/hashlib/_hashlib.cs
index f463224ca..2af22c374 100644
--- a/Src/IronPython.Modules/hashlib/_hashlib.cs
+++ b/Src/IronPython.Modules/hashlib/_hashlib.cs
@@ -3,7 +3,6 @@
// See the LICENSE file in the project root for more information.
using System;
-using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Security.Cryptography;
diff --git a/Src/IronPython.Modules/marshal.cs b/Src/IronPython.Modules/marshal.cs
index 1841e9a93..f431892e7 100644
--- a/Src/IronPython.Modules/marshal.cs
+++ b/Src/IronPython.Modules/marshal.cs
@@ -30,7 +30,7 @@ public static Bytes dumps(object value, int version = PythonMarshal.version) {
return Bytes.Make(MarshalOps.GetBytes(value, version));
}
- public static object loads([BytesLike]IList bytes) {
+ public static object loads([BytesLike] IList bytes) {
return MarshalOps.GetObject(bytes.GetEnumerator());
}
diff --git a/Src/IronPython.Modules/math.cs b/Src/IronPython.Modules/math.cs
index a7f3910a5..6e6dfff2d 100644
--- a/Src/IronPython.Modules/math.cs
+++ b/Src/IronPython.Modules/math.cs
@@ -9,12 +9,10 @@
using System.Linq;
using System.Numerics;
-using Microsoft.Scripting;
-using Microsoft.Scripting.Utils;
-
using IronPython.Runtime;
using IronPython.Runtime.Operations;
-using IronPython.Runtime.Types;
+
+using Microsoft.Scripting.Utils;
[assembly: PythonModule("math", typeof(IronPython.Modules.PythonMath))]
namespace IronPython.Modules {
diff --git a/Src/IronPython.Modules/msvcrt.cs b/Src/IronPython.Modules/msvcrt.cs
index e81c3d119..3ccc6e61a 100644
--- a/Src/IronPython.Modules/msvcrt.cs
+++ b/Src/IronPython.Modules/msvcrt.cs
@@ -5,6 +5,7 @@
#if FEATURE_NATIVE
using Microsoft.Win32.SafeHandles;
+
using System;
using System.ComponentModel;
using System.IO;
@@ -195,34 +196,34 @@ public static void ungetwch(char @char) {
private static int EOF = -1;
private static ushort WEOF = 0xFFFF;
- [DllImport("msvcr100", SetLastError=true, CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
private static extern int _heapmin();
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern int _kbhit();
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern int _getch();
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern int _getche();
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern int _putch(int c);
- [DllImport("msvcr100", SetLastError=true, CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
private static extern int _ungetch(int c);
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern ushort _getwch();
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern ushort _getwche();
- [DllImport("msvcr100", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", CallingConvention = CallingConvention.Cdecl)]
private static extern ushort _putwch(char c);
- [DllImport("msvcr100", SetLastError=true, CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("msvcr100", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
private static extern ushort _ungetwch(ushort c);
#endregion
diff --git a/Src/IronPython.Modules/nt.cs b/Src/IronPython.Modules/nt.cs
index f6f920a3c..e5fe37817 100644
--- a/Src/IronPython.Modules/nt.cs
+++ b/Src/IronPython.Modules/nt.cs
@@ -5,6 +5,7 @@
#nullable enable
using Microsoft.Win32.SafeHandles;
+
using System;
using System.Collections;
using System.Collections.Generic;
@@ -2306,10 +2307,10 @@ private static Bytes ToFsBytes(this IBufferProtocol bp, CodeContext context) {
private static string ConvertToFsString(CodeContext context, [NotNull] object? o, string argname, [CallerMemberName] string? methodname = null)
=> o switch {
- string s => s,
+ string s => s,
ExtensibleString es => es.Value,
- Bytes b => b.ToFsString(context),
- IBufferProtocol bp => bp.ToFsBytes(context).ToFsString(context),
+ Bytes b => b.ToFsString(context),
+ IBufferProtocol bp => bp.ToFsBytes(context).ToFsString(context),
// TODO: Python 3.6: os.PathLike
_ => throw PythonOps.TypeError("{0}: {1} should be string or bytes, not '{2}'", methodname, argname, PythonOps.GetPythonTypeName(o))
};
diff --git a/Src/IronPython.Modules/pwd.cs b/Src/IronPython.Modules/pwd.cs
index 1eb3b015b..a848008f1 100644
--- a/Src/IronPython.Modules/pwd.cs
+++ b/Src/IronPython.Modules/pwd.cs
@@ -5,19 +5,17 @@
#if FEATURE_NATIVE
using System;
+using System.Numerics;
using System.Runtime.InteropServices;
-using Microsoft.Scripting.Runtime;
-
-using IronPython;
using IronPython.Runtime;
using IronPython.Runtime.Operations;
-using System.Numerics;
+using Microsoft.Scripting.Runtime;
[assembly: PythonModule("pwd", typeof(IronPython.Modules.PythonPwd), PlatformsAttribute.PlatformFamily.Unix)]
namespace IronPython.Modules {
-
+
public static class PythonPwd {
public const string __doc__ = @"This module provides access to the Unix password database.
It is available on all Unix versions.
@@ -130,11 +128,11 @@ public static struct_passwd getpwuid(object uid) {
if (uid is int id) {
var pwd = _getpwuid(id);
- if(pwd == IntPtr.Zero) {
+ if (pwd == IntPtr.Zero) {
throw PythonOps.KeyError($"getpwuid(): uid not found: {id}");
}
- return Make(pwd);
+ return Make(pwd);
}
throw PythonOps.TypeError($"integer argument expected, got {PythonOps.GetPythonTypeName(uid)}");
@@ -143,7 +141,7 @@ public static struct_passwd getpwuid(object uid) {
[Documentation("Return the password database entry for the given user name.")]
public static struct_passwd getpwnam(string name) {
var pwd = _getpwnam(name);
- if(pwd == IntPtr.Zero) {
+ if (pwd == IntPtr.Zero) {
throw PythonOps.KeyError($"getpwname(): name not found: {name}");
}
@@ -155,27 +153,27 @@ public static PythonList getpwall() {
var res = new PythonList();
setpwent();
IntPtr val = getpwent();
- while(val != IntPtr.Zero) {
+ while (val != IntPtr.Zero) {
res.Add(Make(val));
val = getpwent();
}
-
+
return res;
}
#region P/Invoke Declarations
- [DllImport("libc", EntryPoint="getpwuid", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", EntryPoint = "getpwuid", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _getpwuid(int uid);
- [DllImport("libc", EntryPoint="getpwnam", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", EntryPoint = "getpwnam", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _getpwnam([MarshalAs(UnmanagedType.LPStr)] string name);
- [DllImport("libc", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern void setpwent();
- [DllImport("libc", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr getpwent();
#endregion
diff --git a/Src/IronPython.Modules/pyexpat.cs b/Src/IronPython.Modules/pyexpat.cs
index 0e68c8a06..a8ead845d 100644
--- a/Src/IronPython.Modules/pyexpat.cs
+++ b/Src/IronPython.Modules/pyexpat.cs
@@ -229,7 +229,7 @@ public static string ErrorString(int errno) {
return null;
}
- public static object ParserCreate(CodeContext context, [ParamDictionary]IDictionary kwArgs\u00F8, params object[] args\u00F8) {
+ public static object ParserCreate(CodeContext context, [ParamDictionary] IDictionary kwArgs\u00F8, params object[] args\u00F8) {
var numArgs = argsø.Length + kwArgsø.Count;
if (numArgs > 3) throw PythonOps.TypeError($"ParserCreate() takes at most 3 arguments ({numArgs} given)");
diff --git a/Src/IronPython.Modules/re.cs b/Src/IronPython.Modules/re.cs
index c2a371819..0d065889e 100644
--- a/Src/IronPython.Modules/re.cs
+++ b/Src/IronPython.Modules/re.cs
@@ -74,14 +74,14 @@ internal enum ReFlags : int {
public const int A = (int)ReFlags.ASCII;
// long forms
- public const int TEMPLATE = (int)ReFlags.TEMPLATE;
+ public const int TEMPLATE = (int)ReFlags.TEMPLATE;
public const int IGNORECASE = (int)ReFlags.IGNORECASE;
- public const int LOCALE = (int)ReFlags.LOCALE;
- public const int MULTILINE = (int)ReFlags.MULTILINE;
- public const int DOTALL = (int)ReFlags.DOTALL;
- public const int UNICODE = (int)ReFlags.UNICODE;
- public const int VERBOSE = (int)ReFlags.VERBOSE;
- public const int ASCII = (int)ReFlags.ASCII;
+ public const int LOCALE = (int)ReFlags.LOCALE;
+ public const int MULTILINE = (int)ReFlags.MULTILINE;
+ public const int DOTALL = (int)ReFlags.DOTALL;
+ public const int UNICODE = (int)ReFlags.UNICODE;
+ public const int VERBOSE = (int)ReFlags.VERBOSE;
+ public const int ASCII = (int)ReFlags.ASCII;
#endregion
diff --git a/Src/IronPython.Modules/resource.cs b/Src/IronPython.Modules/resource.cs
index f83898a1c..ba6f0babb 100644
--- a/Src/IronPython.Modules/resource.cs
+++ b/Src/IronPython.Modules/resource.cs
@@ -5,18 +5,18 @@
#nullable enable
using System;
-using System.Numerics;
using System.Linq;
+using System.Numerics;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
-using Microsoft.Scripting.Runtime;
-
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
+using Microsoft.Scripting.Runtime;
+
[assembly: PythonModule("resource", typeof(IronPython.Modules.PythonResourceModule), PlatformsAttribute.PlatformFamily.Unix)]
namespace IronPython.Modules;
@@ -367,20 +367,20 @@ internal struct rusage {
public timeval ru_utime; // user CPU time used
public timeval ru_stime; // system CPU time used
- public long ru_maxrss; // maximum resident set size
- public long ru_ixrss; // integral shared memory size
- public long ru_idrss; // integral unshared data size
- public long ru_isrss; // integral unshared stack size
- public long ru_minflt; // page reclaims (soft page faults)
- public long ru_majflt; // page faults (hard page faults)
- public long ru_nswap; // swaps
- public long ru_inblock; // block input operations
- public long ru_oublock; // block output operations
- public long ru_msgsnd; // IPC messages sent
- public long ru_msgrcv; // IPC messages received
- public long ru_nsignals; // signals received
- public long ru_nvcsw; // voluntary context switches
- public long ru_nivcsw; // involuntary context switches
+ public long ru_maxrss; // maximum resident set size
+ public long ru_ixrss; // integral shared memory size
+ public long ru_idrss; // integral unshared data size
+ public long ru_isrss; // integral unshared stack size
+ public long ru_minflt; // page reclaims (soft page faults)
+ public long ru_majflt; // page faults (hard page faults)
+ public long ru_nswap; // swaps
+ public long ru_inblock; // block input operations
+ public long ru_oublock; // block output operations
+ public long ru_msgsnd; // IPC messages sent
+ public long ru_msgrcv; // IPC messages received
+ public long ru_nsignals; // signals received
+ public long ru_nvcsw; // voluntary context switches
+ public long ru_nivcsw; // involuntary context switches
}
#pragma warning restore CS0649
diff --git a/Src/IronPython.Modules/select.cs b/Src/IronPython.Modules/select.cs
index f5f8c2ed3..9d7e9a5a3 100644
--- a/Src/IronPython.Modules/select.cs
+++ b/Src/IronPython.Modules/select.cs
@@ -40,7 +40,7 @@ public static class PythonSelect {
+ "Note that select() on IronPython works only with sockets; it will not work with\n"
+ "files or other objects."
)]
- public static PythonTuple select(CodeContext/*!*/ context, object iwtd, object owtd, object ewtd, object timeout=null) {
+ public static PythonTuple select(CodeContext/*!*/ context, object iwtd, object owtd, object ewtd, object timeout = null) {
PythonList readerList, writerList, errorList;
Dictionary readerOriginals, writerOriginals, errorOriginals;
ProcessSocketSequence(context, iwtd, out readerList, out readerOriginals);
@@ -57,7 +57,7 @@ public static PythonTuple select(CodeContext/*!*/ context, object iwtd, object o
if (!Converter.TryConvertToDouble(timeout, out timeoutSeconds)) {
throw PythonOps.TypeErrorForTypeMismatch("float or None", timeout);
}
- timeoutMicroseconds = (int) (1000000 * timeoutSeconds);
+ timeoutMicroseconds = (int)(1000000 * timeoutSeconds);
}
try {
diff --git a/Src/IronPython.Modules/signal.cs b/Src/IronPython.Modules/signal.cs
index 1ae2de2f8..b42c63fdf 100644
--- a/Src/IronPython.Modules/signal.cs
+++ b/Src/IronPython.Modules/signal.cs
@@ -160,7 +160,7 @@ public static object signal(CodeContext/*!*/ context, int sig, object action) {
PythonFunction result = action as PythonFunction;
if (result == null) {
//It could still be something like a type that implements __call__
- if (! PythonOps.IsCallable(context, action)) {
+ if (!PythonOps.IsCallable(context, action)) {
throw PythonOps.TypeError("signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
}
}
@@ -191,11 +191,11 @@ public static void set_wakeup_fd(CodeContext/*!*/ context, uint fd) {
}
private static readonly object _PythonSignalStateKey = new object();
-
+
private static PythonSignalState GetPythonSignalState(CodeContext/*!*/ context) {
return (PythonSignalState)context.LanguageContext.GetModuleState(_PythonSignalStateKey);
}
-
+
private static void SetPythonSignalState(CodeContext/*!*/ context, PythonSignalState pss) {
context.LanguageContext.SetModuleState(_PythonSignalStateKey, pss);
}
diff --git a/Src/IronPython.Modules/spwd.cs b/Src/IronPython.Modules/spwd.cs
index 9445f7341..a477f56d7 100644
--- a/Src/IronPython.Modules/spwd.cs
+++ b/Src/IronPython.Modules/spwd.cs
@@ -7,16 +7,14 @@
using System;
using System.Runtime.InteropServices;
-using Microsoft.Scripting.Runtime;
-
using IronPython.Runtime;
using IronPython.Runtime.Operations;
-using System.Numerics;
+using Microsoft.Scripting.Runtime;
[assembly: PythonModule("spwd", typeof(IronPython.Modules.PythonSpwd), PlatformsAttribute.PlatformFamily.Unix)]
namespace IronPython.Modules {
-
+
public static class PythonSpwd {
public const string __doc__ = @"This module provides access to the Unix shadow password database.
It is available on various Unix versions.
@@ -41,7 +39,7 @@ private struct spwd {
public int sp_inact;
public int sp_expire;
public int sp_flag;
- };
+ };
[PythonType("struct_spwd")]
[Documentation(@"spwd.struct_spwd: Results from getsp*() routines.
@@ -54,7 +52,7 @@ public class struct_spwd : PythonTuple {
private const int LENGTH = 9;
internal struct_spwd(string sp_nam, string sp_pwd, int sp_lstchg, int sp_min, int sp_max, int sp_warn, int sp_inact, int sp_expire, int sp_flag) :
- base(new object[] { sp_nam ,sp_pwd, sp_lstchg, sp_min, sp_max, sp_warn, sp_inact, sp_expire, sp_flag }) {
+ base(new object[] { sp_nam, sp_pwd, sp_lstchg, sp_min, sp_max, sp_warn, sp_inact, sp_expire, sp_flag }) {
}
[Documentation("login name")]
@@ -97,7 +95,7 @@ private static struct_spwd Make(IntPtr pwd) {
[Documentation("Return the shadow password database entry for the given user name.")]
public static struct_spwd getspnam(string name) {
var pwd = _getspnam(name);
- if(pwd == IntPtr.Zero) {
+ if (pwd == IntPtr.Zero) {
throw PythonOps.KeyError($"getspnam(): name not found");
}
@@ -109,24 +107,24 @@ public static PythonList getspall() {
var res = new PythonList();
setspent();
IntPtr val = getspent();
- while(val != IntPtr.Zero) {
+ while (val != IntPtr.Zero) {
res.Add(Make(val));
val = getspent();
}
-
+
return res;
}
#region P/Invoke Declarations
- [DllImport("libc", EntryPoint="getspnam", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", EntryPoint = "getspnam", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr _getspnam([MarshalAs(UnmanagedType.LPStr)] string name);
- [DllImport("libc", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern void setspent();
- [DllImport("libc", CallingConvention=CallingConvention.Cdecl)]
+ [DllImport("libc", CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr getspent();
#endregion
diff --git a/Src/IronPython.Modules/winreg.cs b/Src/IronPython.Modules/winreg.cs
index 5b80836d2..22270900b 100644
--- a/Src/IronPython.Modules/winreg.cs
+++ b/Src/IronPython.Modules/winreg.cs
@@ -4,8 +4,6 @@
#if FEATURE_REGISTRY
-using Microsoft.Win32;
-using Microsoft.Win32.SafeHandles;
using System;
using System.Collections.Concurrent;
using System.ComponentModel;
@@ -22,6 +20,9 @@
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Types;
+using Microsoft.Win32;
+using Microsoft.Win32.SafeHandles;
+
[assembly: PythonModule("winreg", typeof(IronPython.Modules.PythonWinReg), PlatformsAttribute.PlatformFamily.Windows)]
namespace IronPython.Modules {
[SupportedOSPlatform("windows")]
diff --git a/Src/IronPython.Modules/winsound.cs b/Src/IronPython.Modules/winsound.cs
index 56cb0cfc8..327bf04d1 100644
--- a/Src/IronPython.Modules/winsound.cs
+++ b/Src/IronPython.Modules/winsound.cs
@@ -7,7 +7,6 @@
#nullable enable
using System;
-using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
@@ -132,7 +131,7 @@ public static void Beep(CodeContext/*!*/ context, int freq, int dur) {
}
[Documentation("MessageBeep(x) - call Windows MessageBeep(x). x defaults to MB_OK.")]
- public static void MessageBeep(CodeContext/*!*/ context, int x=MB_OK) {
+ public static void MessageBeep(CodeContext/*!*/ context, int x = MB_OK) {
MessageBeep(x);
}
diff --git a/Src/IronPython.Modules/xxsubtype.cs b/Src/IronPython.Modules/xxsubtype.cs
index 8980fc8c1..db2c251ec 100644
--- a/Src/IronPython.Modules/xxsubtype.cs
+++ b/Src/IronPython.Modules/xxsubtype.cs
@@ -2,17 +2,16 @@
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
-using System;
using System.Collections.Generic;
-using Microsoft.Scripting;
-
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
+using Microsoft.Scripting;
+
[assembly: PythonModule("xxsubtype", typeof(IronPython.Modules.xxsubtype))]
-namespace IronPython.Modules {
+namespace IronPython.Modules {
///
/// Samples on how to subtype built-in types from C#
///
@@ -50,12 +49,12 @@ public void setstate(int value) {
state = value;
}
- public static object staticmeth([ParamDictionary]IDictionary dict, params object[] args) {
+ public static object staticmeth([ParamDictionary] IDictionary dict, params object[] args) {
return PythonTuple.MakeTuple(null, PythonTuple.MakeTuple(args), dict);
}
[ClassMethod]
- public static object classmeth(PythonType cls, [ParamDictionary]IDictionary dict, params object[] args) {
+ public static object classmeth(PythonType cls, [ParamDictionary] IDictionary dict, params object[] args) {
return PythonTuple.MakeTuple(cls, PythonTuple.MakeTuple(args), dict);
}
}
diff --git a/Src/IronPython.Modules/zipimport.cs b/Src/IronPython.Modules/zipimport.cs
index f1d97b0d2..62bb9c8f7 100644
--- a/Src/IronPython.Modules/zipimport.cs
+++ b/Src/IronPython.Modules/zipimport.cs
@@ -1,6 +1,6 @@
using System;
-using System.IO;
using System.Collections.Generic;
+using System.IO;
using System.Runtime.CompilerServices;
using IronPython.Runtime;
@@ -10,7 +10,6 @@
using IronPython.Zlib;
using Microsoft.Scripting;
-using Microsoft.Scripting.Utils;
using Microsoft.Scripting.Runtime;
[assembly: PythonModule("zipimport", typeof(IronPython.Runtime.ZipImportModule))]
diff --git a/Src/IronPython.Modules/zlib/Compress.cs b/Src/IronPython.Modules/zlib/Compress.cs
index 4f07b7fdf..e9903d2a9 100644
--- a/Src/IronPython.Modules/zlib/Compress.cs
+++ b/Src/IronPython.Modules/zlib/Compress.cs
@@ -6,33 +6,30 @@
//
using System;
-using System.Collections.Generic;
using System.Linq;
-using System.Runtime.InteropServices;
+
using ComponentAce.Compression.Libs.ZLib;
+
using IronPython.Runtime;
using IronPython.Runtime.Operations;
+
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
-namespace IronPython.Zlib
-{
+namespace IronPython.Zlib {
[PythonType]
- public class Compress
- {
+ public class Compress {
private const int Z_OK = ZlibModule.Z_OK;
private const int Z_BUF_ERROR = ZlibModule.Z_BUF_ERROR;
private const int Z_STREAM_END = ZlibModule.Z_STREAM_END;
-
+
private const int Z_NO_FLUSH = ZlibModule.Z_NO_FLUSH;
private const int Z_FINISH = ZlibModule.Z_FINISH;
- internal Compress(int level, int method, int wbits, int memlevel, int strategy)
- {
+ internal Compress(int level, int method, int wbits, int memlevel, int strategy) {
zst = new ZStream();
int err = zst.DeflateInit(level, wbits);
- switch(err)
- {
+ switch (err) {
case ZlibModule.Z_OK:
break;
@@ -49,8 +46,7 @@ internal Compress(int level, int method, int wbits, int memlevel, int strategy)
After calling this function, some of the input data may still
be stored in internal buffers for later processing.
Call the flush() method to clear these buffers.")]
- public Bytes compress([NotNone] IBufferProtocol data)
- {
+ public Bytes compress([NotNone] IBufferProtocol data) {
using var buffer = data.GetBuffer();
byte[] input = buffer.AsUnsafeArray() ?? buffer.ToArray();
byte[] output = new byte[ZlibModule.DEFAULTALLOC];
@@ -65,8 +61,7 @@ public Bytes compress([NotNone] IBufferProtocol data)
int err = zst.deflate(Z_NO_FLUSH);
- while(err == Z_OK && zst.avail_out == 0)
- {
+ while (err == Z_OK && zst.avail_out == 0) {
int length = output.Length;
Array.Resize(ref output, output.Length * 2);
@@ -76,8 +71,7 @@ public Bytes compress([NotNone] IBufferProtocol data)
err = zst.deflate(Z_NO_FLUSH);
}
- if(err != Z_OK && err != Z_BUF_ERROR)
- {
+ if (err != Z_OK && err != Z_BUF_ERROR) {
throw ZlibModule.zlib_error(this.zst, err, "while compressing");
}
@@ -90,12 +84,10 @@ public Bytes compress([NotNone] IBufferProtocol data)
default value used when mode is not specified is Z_FINISH.
If mode == Z_FINISH, the compressor object can no longer be used after
calling the flush() method. Otherwise, more data can still be compressed.")]
- public Bytes flush(int mode=Z_FINISH)
- {
+ public Bytes flush(int mode = Z_FINISH) {
byte[] output = new byte[ZlibModule.DEFAULTALLOC];
- if(mode == Z_NO_FLUSH)
- {
+ if (mode == Z_NO_FLUSH) {
return Bytes.Empty;
}
@@ -106,8 +98,7 @@ public Bytes flush(int mode=Z_FINISH)
zst.avail_out = output.Length;
int err = zst.deflate((FlushStrategy)mode);
- while(err == Z_OK && zst.avail_out == 0)
- {
+ while (err == Z_OK && zst.avail_out == 0) {
int old_length = output.Length;
Array.Resize(ref output, output.Length * 2);
@@ -117,16 +108,12 @@ public Bytes flush(int mode=Z_FINISH)
err = zst.deflate((FlushStrategy)mode);
}
- if(err == Z_STREAM_END && mode == Z_FINISH)
- {
+ if (err == Z_STREAM_END && mode == Z_FINISH) {
err = zst.deflateEnd();
- if(err != Z_OK)
- {
+ if (err != Z_OK) {
throw ZlibModule.zlib_error(this.zst, err, "from deflateEnd()");
}
- }
- else if(err != Z_OK && err != Z_BUF_ERROR)
- {
+ } else if (err != Z_OK && err != Z_BUF_ERROR) {
throw ZlibModule.zlib_error(this.zst, err, "while flushing");
}
@@ -141,8 +128,7 @@ public Bytes flush(int mode=Z_FINISH)
private ZStream zst;
- private static Bytes GetBytes(byte[] bytes, int index, int count)
- {
+ private static Bytes GetBytes(byte[] bytes, int index, int count) {
var res = new byte[count];
Array.Copy(bytes, index, res, 0, count);
return Bytes.Make(res);
diff --git a/Src/IronPython.Modules/zlib/Decompress.cs b/Src/IronPython.Modules/zlib/Decompress.cs
index c0965e6ad..528e36cf2 100644
--- a/Src/IronPython.Modules/zlib/Decompress.cs
+++ b/Src/IronPython.Modules/zlib/Decompress.cs
@@ -6,20 +6,19 @@
//
using System;
-using System.Collections.Generic;
using System.Linq;
-using System.Runtime.InteropServices;
+
using ComponentAce.Compression.Libs.ZLib;
+
using IronPython.Runtime;
using IronPython.Runtime.Operations;
+
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
-namespace IronPython.Zlib
-{
+namespace IronPython.Zlib {
[PythonType]
- public class Decompress
- {
+ public class Decompress {
private const int Z_OK = ZlibModule.Z_OK;
private const int Z_STREAM_END = ZlibModule.Z_STREAM_END;
private const int Z_BUF_ERROR = ZlibModule.Z_BUF_ERROR;
@@ -27,12 +26,10 @@ public class Decompress
private const int Z_SYNC_FLUSH = ZlibModule.Z_SYNC_FLUSH;
private const int Z_FINISH = ZlibModule.Z_FINISH;
- internal Decompress(int wbits)
- {
+ internal Decompress(int wbits) {
zst = new ZStream();
int err = zst.inflateInit(wbits);
- switch(err)
- {
+ switch (err) {
case ZlibModule.Z_OK:
break;
@@ -59,9 +56,8 @@ Call the flush() method to clear these buffers.
If the max_length parameter is specified then the return value will be
no longer than max_length. Unconsumed input data will be stored in
the unconsumed_tail attribute.")]
- public Bytes decompress([NotNone] IBufferProtocol data, int max_length=0)
- {
- if(max_length < 0) throw new ArgumentException("max_length must be greater than zero");
+ public Bytes decompress([NotNone] IBufferProtocol data, int max_length = 0) {
+ if (max_length < 0) throw new ArgumentException("max_length must be greater than zero");
using var buffer = data.GetBuffer();
byte[] input = buffer.AsUnsafeArray() ?? buffer.ToArray();
@@ -77,9 +73,8 @@ public Bytes decompress([NotNone] IBufferProtocol data, int max_length=0)
int err = zst.inflate(FlushStrategy.Z_SYNC_FLUSH);
- while(err == Z_OK && zst.avail_out == 0)
- {
- if(max_length > 0 && output.Length >= max_length)
+ while (err == Z_OK && zst.avail_out == 0) {
+ if (max_length > 0 && output.Length >= max_length)
break;
int old_length = output.Length;
@@ -90,18 +85,14 @@ public Bytes decompress([NotNone] IBufferProtocol data, int max_length=0)
err = zst.inflate(FlushStrategy.Z_SYNC_FLUSH);
}
- if(max_length > 0)
- {
+ if (max_length > 0) {
unconsumed_tail = GetBytes(zst.next_in, zst.next_in_index, zst.avail_in);
}
- if(err == Z_STREAM_END)
- {
+ if (err == Z_STREAM_END) {
unused_data += GetBytes(zst.next_in, zst.next_in_index, zst.avail_in);
eof = true;
- }
- else if(err != Z_OK && err != Z_BUF_ERROR)
- {
+ } else if (err != Z_OK && err != Z_BUF_ERROR) {
throw ZlibModule.zlib_error(this.zst, err, "while decompressing");
}
@@ -115,9 +106,8 @@ public Bytes decompress([NotNone] IBufferProtocol data, int max_length=0)
output buffer.
The decompressor object can no longer be used after this call.")]
- public Bytes flush(int length=ZlibModule.DEFAULTALLOC)
- {
- if(length < 1)
+ public Bytes flush(int length = ZlibModule.DEFAULTALLOC) {
+ if (length < 1)
throw PythonOps.ValueError("length must be greater than 0.");
byte[] output = new byte[length];
@@ -129,8 +119,7 @@ public Bytes flush(int length=ZlibModule.DEFAULTALLOC)
int err = zst.inflate(FlushStrategy.Z_FINISH);
- while((err == Z_OK || err == Z_BUF_ERROR) &&zst.avail_out == 0)
- {
+ while ((err == Z_OK || err == Z_BUF_ERROR) && zst.avail_out == 0) {
int old_length = output.Length;
Array.Resize(ref output, output.Length * 2);
zst.next_out = output;
@@ -139,11 +128,9 @@ public Bytes flush(int length=ZlibModule.DEFAULTALLOC)
err = zst.inflate(FlushStrategy.Z_FINISH);
}
- if(err == Z_STREAM_END)
- {
+ if (err == Z_STREAM_END) {
err = zst.inflateEnd();
- if(err != Z_OK)
- {
+ if (err != Z_OK) {
throw ZlibModule.zlib_error(this.zst, err, "from inflateEnd()");
}
}
@@ -159,8 +146,7 @@ public Bytes flush(int length=ZlibModule.DEFAULTALLOC)
private ZStream zst;
- private static Bytes GetBytes(byte[] bytes, int index, int count)
- {
+ private static Bytes GetBytes(byte[] bytes, int index, int count) {
var res = new byte[count];
Array.Copy(bytes, index, res, 0, count);
return Bytes.Make(res);
diff --git a/Src/IronPython.Modules/zlib/ZlibModule.cs b/Src/IronPython.Modules/zlib/ZlibModule.cs
index 208c61417..940739236 100644
--- a/Src/IronPython.Modules/zlib/ZlibModule.cs
+++ b/Src/IronPython.Modules/zlib/ZlibModule.cs
@@ -6,24 +6,23 @@
//
using System;
-using System.Collections.Generic;
using System.Linq;
-using System.Numerics;
using System.Runtime.CompilerServices;
+
using ComponentAce.Compression.Libs.ZLib;
+
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
+
using Microsoft.Scripting.Runtime;
using Microsoft.Scripting.Utils;
[assembly: PythonModule("zlib", typeof(IronPython.Zlib.ZlibModule))]
-namespace IronPython.Zlib
-{
- public static class ZlibModule
- {
+namespace IronPython.Zlib {
+ public static class ZlibModule {
public const string __doc__ = @"The functions in this module allow compression and decompression using the
zlib library, which is based on GNU zip.
@@ -73,8 +72,7 @@ public static class ZlibModule
An optional starting value can be specified. The returned checksum is
a signed integer.")]
- public static int adler32([NotNone] IBufferProtocol data, long value=1L)
- {
+ public static int adler32([NotNone] IBufferProtocol data, long value = 1L) {
using var buffer = data.GetBuffer();
return (int)Adler32.GetAdler32Checksum(value, buffer.AsUnsafeArray() ?? buffer.ToArray(), 0, buffer.NumBytes());
}
@@ -91,8 +89,7 @@ public static object crc32([NotNone] IBufferProtocol data, uint value = 0)
Optional arg level is the compression level, in 1-9.")]
public static Bytes compress([NotNone] IBufferProtocol data,
- int level=Z_DEFAULT_COMPRESSION)
- {
+ int level = Z_DEFAULT_COMPRESSION) {
using var buffer = data.GetBuffer();
byte[] input = buffer.AsUnsafeArray() ?? buffer.ToArray();
byte[] output = new byte[input.Length + input.Length / 1000 + 12 + 1];
@@ -104,15 +101,14 @@ public static Bytes compress([NotNone] IBufferProtocol data,
zst.avail_out = output.Length;
int err = zst.DeflateInit(level);
- switch(err)
- {
+ switch (err) {
case (Z_OK):
break;
-
+
case (Z_STREAM_ERROR):
throw PythonOps.CreateThrowable(error,
"Bad compression level");
-
+
default:
zst.deflateEnd();
zlib_error(zst, err, "while compressing data");
@@ -121,16 +117,14 @@ public static Bytes compress([NotNone] IBufferProtocol data,
err = zst.deflate(FlushStrategy.Z_FINISH);
- if(err != Z_STREAM_END)
- {
+ if (err != Z_STREAM_END) {
zst.deflateEnd();
throw zlib_error(zst, err, "while compressing data");
}
err = zst.deflateEnd();
- if(err == Z_OK)
- {
+ if (err == Z_OK) {
var res = new byte[(int)zst.total_out];
Array.Copy(output, res, res.Length);
return Bytes.Make(res);
@@ -143,12 +137,11 @@ public static Bytes compress([NotNone] IBufferProtocol data,
Optional arg level is the compression level, in 1-9.")]
public static Compress compressobj(
- int level=Z_DEFAULT_COMPRESSION,
- int method=DEFLATED,
- int wbits=MAX_WBITS,
- int memlevel=DEF_MEM_LEVEL,
- int strategy=Z_DEFAULT_STRATEGY)
- {
+ int level = Z_DEFAULT_COMPRESSION,
+ int method = DEFLATED,
+ int wbits = MAX_WBITS,
+ int memlevel = DEF_MEM_LEVEL,
+ int strategy = Z_DEFAULT_STRATEGY) {
return new Compress(level, method, wbits, memlevel, strategy);
}
@@ -157,9 +150,8 @@ public static Compress compressobj(
Optional arg wbits is the window buffer size. Optional arg bufsize is
the initial output buffer size.")]
public static Bytes decompress([NotNone] IBufferProtocol data,
- int wbits=MAX_WBITS,
- int bufsize=DEFAULTALLOC)
- {
+ int wbits = MAX_WBITS,
+ int bufsize = DEFAULTALLOC) {
using var buffer = data.GetBuffer();
var bytes = Decompress(buffer.AsUnsafeArray() ?? buffer.ToArray(), wbits, bufsize);
return Bytes.Make(bytes);
@@ -168,30 +160,24 @@ public static Bytes decompress([NotNone] IBufferProtocol data,
[Documentation(@"decompressobj([wbits]) -- Return a decompressor object.
Optional arg wbits is the window buffer size.")]
- public static Decompress decompressobj(int wbits=MAX_WBITS)
- {
+ public static Decompress decompressobj(int wbits = MAX_WBITS) {
return new Decompress(wbits);
}
[SpecialName]
- public static void PerformModuleReload(PythonContext context, PythonDictionary dict)
- {
+ public static void PerformModuleReload(PythonContext context, PythonDictionary dict) {
error = context.EnsureModuleException("zlib.error", PythonExceptions.Exception, dict, "error", "zlib");
}
public static PythonType error;
- internal static Exception MakeError(params object[] args)
- {
+ internal static Exception MakeError(params object[] args) {
return PythonOps.CreateThrowable(error, args);
}
- internal static Exception zlib_error(ZStream zst, int err, string msg)
- {
+ internal static Exception zlib_error(ZStream zst, int err, string msg) {
string zmsg = zst.msg;
- if(zmsg == null)
- {
- switch(err)
- {
+ if (zmsg == null) {
+ switch (err) {
case Z_BUF_ERROR:
zmsg = "incomplete or truncated stream";
break;
@@ -204,15 +190,14 @@ internal static Exception zlib_error(ZStream zst, int err, string msg)
}
}
- if(zmsg == null)
+ if (zmsg == null)
return MakeError(string.Format("Error {0} {1}", err, msg));
else
return MakeError(string.Format("Error {0} {1}: {2}", err, msg, zmsg));
}
[PythonHidden]
- internal static byte[] Decompress(byte[] input, int wbits=MAX_WBITS, int bufsize=DEFAULTALLOC)
- {
+ internal static byte[] Decompress(byte[] input, int wbits = MAX_WBITS, int bufsize = DEFAULTALLOC) {
byte[] outputBuffer = new byte[bufsize];
byte[] output = new byte[bufsize];
int outputOffset = 0;
@@ -224,26 +209,20 @@ internal static byte[] Decompress(byte[] input, int wbits=MAX_WBITS, int bufsize
zst.avail_out = outputBuffer.Length;
int err = zst.inflateInit(wbits);
- if(err != Z_OK)
- {
+ if (err != Z_OK) {
zst.inflateEnd();
throw zlib_error(zst, err, "while preparing to decompress data");
}
- do
- {
+ do {
err = zst.inflate(FlushStrategy.Z_FINISH);
- if(err != Z_STREAM_END)
- {
- if(err == Z_BUF_ERROR && zst.avail_out > 0)
- {
+ if (err != Z_STREAM_END) {
+ if (err == Z_BUF_ERROR && zst.avail_out > 0) {
zst.inflateEnd();
throw zlib_error(zst, err, "while decompressing data");
- }
- else if(err == Z_OK || (err == Z_BUF_ERROR && zst.avail_out == 0))
- {
+ } else if (err == Z_OK || (err == Z_BUF_ERROR && zst.avail_out == 0)) {
// copy to the output and reset the buffer
- if(outputOffset + outputBuffer.Length > output.Length)
+ if (outputOffset + outputBuffer.Length > output.Length)
Array.Resize(ref output, output.Length * 2);
Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length);
@@ -252,23 +231,20 @@ internal static byte[] Decompress(byte[] input, int wbits=MAX_WBITS, int bufsize
zst.next_out = outputBuffer;
zst.avail_out = outputBuffer.Length;
zst.next_out_index = 0;
- }
- else
- {
+ } else {
zst.inflateEnd();
throw zlib_error(zst, err, "while decompressing data");
}
}
- } while(err != Z_STREAM_END);
+ } while (err != Z_STREAM_END);
err = zst.inflateEnd();
- if(err != Z_OK)
- {
+ if (err != Z_OK) {
throw zlib_error(zst, err, "while finishing data decompression");
}
- if(outputOffset + outputBuffer.Length - zst.avail_out > output.Length)
+ if (outputOffset + outputBuffer.Length - zst.avail_out > output.Length)
Array.Resize(ref output, output.Length * 2);
Array.Copy(outputBuffer, 0, output, outputOffset, outputBuffer.Length - zst.avail_out);
diff --git a/Src/IronPython.Modules/zlib/zlib.net/Adler32.cs b/Src/IronPython.Modules/zlib/zlib.net/Adler32.cs
index aa3f973b9..827b0f019 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/Adler32.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/Adler32.cs
@@ -44,70 +44,60 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* and contributors of zlib.
*/
-using System;
-
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
///
/// This class represents adler32 checksum algorithm.
///
- public static class Adler32
- {
- // largest prime smaller than 65536
- private const int BASE = 65521;
- // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
- private const int NMAX = 5552;
-
+ public static class Adler32 {
+ // largest prime smaller than 65536
+ private const int BASE = 65521;
+ // NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1
+ private const int NMAX = 5552;
+
///
/// This static method returns adler32 checksum of the buffer data
///
- public static long GetAdler32Checksum(long adler, byte[] buf, int index, int len)
- {
- if (buf == null)
- {
- return 1L;
- }
-
- long s1 = adler & 0xffff;
- long s2 = (adler >> 16) & 0xffff;
- int k;
-
- while (len > 0)
- {
- k = len < NMAX?len:NMAX;
- len -= k;
- while (k >= 16)
- {
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- s1 += (buf[index++] & 0xff); s2 += s1;
- k -= 16;
- }
- if (k != 0)
- {
- do
- {
- s1 += (buf[index++] & 0xff); s2 += s1;
- }
- while (--k != 0);
- }
- s1 %= BASE;
- s2 %= BASE;
- }
- return (s2 << 16) | s1;
- }
- }
+ public static long GetAdler32Checksum(long adler, byte[] buf, int index, int len) {
+ if (buf == null) {
+ return 1L;
+ }
+
+ long s1 = adler & 0xffff;
+ long s2 = (adler >> 16) & 0xffff;
+ int k;
+
+ while (len > 0) {
+ k = len < NMAX ? len : NMAX;
+ len -= k;
+ while (k >= 16) {
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ k -= 16;
+ }
+ if (k != 0) {
+ do {
+ s1 += (buf[index++] & 0xff); s2 += s1;
+ }
+ while (--k != 0);
+ }
+ s1 %= BASE;
+ s2 %= BASE;
+ }
+ return (s2 << 16) | s1;
+ }
+ }
}
\ No newline at end of file
diff --git a/Src/IronPython.Modules/zlib/zlib.net/Deflate.cs b/Src/IronPython.Modules/zlib/zlib.net/Deflate.cs
index 59ab2d132..02f124f20 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/Deflate.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/Deflate.cs
@@ -44,22 +44,19 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
///
/// Implementation of the Deflate compression algorithm.
///
- public sealed class Deflate
- {
+ public sealed class Deflate {
#region Nested class
///
/// Deflate algorithm configuration parameters class
///
- internal class Config
- {
+ internal class Config {
///
/// reduce lazy search above this match length
///
@@ -78,12 +75,11 @@ internal class Config
internal int max_chain;
internal int func;
-
+
///
/// Constructor which initializes class inner fields
///
- internal Config(int good_length, int max_lazy, int nice_length, int max_chain, int func)
- {
+ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, int func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
@@ -105,7 +101,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
/// Defalult compression method
///
public const int Z_DEFAULT_COMPRESSION = -1;
-
+
///
/// Default memory level
///
@@ -115,7 +111,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
private const int STORED = 0;
private const int FAST = 1;
private const int SLOW = 2;
-
+
///
/// Deflate class congiration table
///
@@ -257,7 +253,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
///
/// LZ77 Window size (32K by default)
///
- private int w_size;
+ private int w_size;
///
/// log2(w_size) (8..16)
@@ -387,7 +383,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
/// favor or force Huffman coding
///
private CompressionStrategy strategy;
-
+
///
/// Use a faster search when the previous match is longer than this
///
@@ -407,7 +403,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
/// distance tree
///
private short[] dyn_dtree;
-
+
///
/// Huffman tree for bit lengths
///
@@ -421,7 +417,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
///
/// desc for distance tree
///
- private Tree d_desc = new Tree();
+ private Tree d_desc = new Tree();
///
/// desc for bit length tree
@@ -535,8 +531,7 @@ internal Config(int good_length, int max_lazy, int nice_length, int max_chain, i
///
/// Default constructor
///
- internal Deflate()
- {
+ internal Deflate() {
dyn_ltree = new short[HEAP_SIZE * 2];
dyn_dtree = new short[(2 * D_CODES + 1) * 2]; // distance tree
bl_tree = new short[(2 * BL_CODES + 1) * 2]; // Huffman tree for bit lengths
@@ -545,8 +540,7 @@ internal Deflate()
///
/// Initialization
///
- private void lm_init()
- {
+ private void lm_init() {
window_size = 2 * w_size;
Array.Clear(head, 0, hash_size);
@@ -568,8 +562,7 @@ private void lm_init()
///
/// Initialize the tree data structures for a new zlib stream.
///
- private void tr_init()
- {
+ private void tr_init() {
l_desc.DynTree = dyn_ltree;
l_desc.StatDesc = StaticTree.static_l_desc;
@@ -591,8 +584,7 @@ private void tr_init()
///
/// Initializes block
///
- private void init_block()
- {
+ private void init_block() {
// Initialize the trees.
for (int i = 0; i < L_CODES; i++)
dyn_ltree[i * 2] = 0;
@@ -612,15 +604,12 @@ private void init_block()
/// when the heap property is re-established (each father smaller than its
/// two sons).
///
- internal void pqdownheap(short[] tree, int k)
- {
+ internal void pqdownheap(short[] tree, int k) {
int v = heap[k];
int j = k << 1; // left son of k
- while (j <= heap_len)
- {
+ while (j <= heap_len) {
// Set j to the smallest of the two sons:
- if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth))
- {
+ if (j < heap_len && smaller(tree, heap[j + 1], heap[j], depth)) {
j++;
}
// Exit if v is smaller than both sons
@@ -635,8 +624,7 @@ internal void pqdownheap(short[] tree, int k)
heap[k] = v;
}
- internal static bool smaller(short[] tree, int n, int m, byte[] depth)
- {
+ internal static bool smaller(short[] tree, int n, int m, byte[] depth) {
return (tree[n * 2] < tree[m * 2] || (tree[n * 2] == tree[m * 2] && depth[n] <= depth[m]));
}
@@ -644,8 +632,7 @@ internal static bool smaller(short[] tree, int n, int m, byte[] depth)
/// Scan a literal or distance tree to determine the frequencies of the codes
/// in the bit length tree.
///
- private void scan_tree(short[] tree, int max_code)
- {
+ private void scan_tree(short[] tree, int max_code) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
@@ -654,49 +641,34 @@ private void scan_tree(short[] tree, int max_code)
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
- if (nextlen == 0)
- {
+ if (nextlen == 0) {
max_count = 138; min_count = 3;
}
tree[(max_code + 1) * 2 + 1] = (short)ZLibUtil.Identity(0xffff); // guard
- for (n = 0; n <= max_code; n++)
- {
+ for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1];
- if (++count < max_count && curlen == nextlen)
- {
+ if (++count < max_count && curlen == nextlen) {
continue;
}
- if (count < min_count)
- {
+ if (count < min_count) {
bl_tree[curlen * 2] = (short)(bl_tree[curlen * 2] + count);
- }
- else if (curlen != 0)
- {
+ } else if (curlen != 0) {
if (curlen != prevlen)
bl_tree[curlen * 2]++;
bl_tree[REP_3_6 * 2]++;
- }
- else if (count <= 10)
- {
+ } else if (count <= 10) {
bl_tree[REPZ_3_10 * 2]++;
- }
- else
- {
+ } else {
bl_tree[REPZ_11_138 * 2]++;
}
count = 0; prevlen = curlen;
- if (nextlen == 0)
- {
+ if (nextlen == 0) {
max_count = 138; min_count = 3;
- }
- else if (curlen == nextlen)
- {
+ } else if (curlen == nextlen) {
max_count = 6; min_count = 3;
- }
- else
- {
+ } else {
max_count = 7; min_count = 4;
}
}
@@ -706,8 +678,7 @@ private void scan_tree(short[] tree, int max_code)
/// Construct the Huffman tree for the bit lengths and return the index in
/// bl_order of the last bit length code to send.
///
- private int build_bl_tree()
- {
+ private int build_bl_tree() {
int max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
@@ -722,8 +693,7 @@ private int build_bl_tree()
// Determine the number of bit length codes to send. The pkzip format
// requires that at least 4 bit length codes be sent. (appnote.txt says
// 3 but the actual value used is 4.)
- for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--)
- {
+ for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {
if (bl_tree[ZLibUtil.bl_order[max_blindex] * 2 + 1] != 0)
break;
}
@@ -738,15 +708,13 @@ private int build_bl_tree()
/// lengths of the bit length codes, the literal tree and the distance tree.
/// IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
///
- private void send_all_trees(int lcodes, int dcodes, int blcodes)
- {
+ private void send_all_trees(int lcodes, int dcodes, int blcodes) {
int rank; // index in bl_order
send_bits(lcodes - 257, 5); // not +255 as stated in appnote.txt
send_bits(dcodes - 1, 5);
send_bits(blcodes - 4, 4); // not -3 as stated in appnote.txt
- for (rank = 0; rank < blcodes; rank++)
- {
+ for (rank = 0; rank < blcodes; rank++) {
send_bits(bl_tree[ZLibUtil.bl_order[rank] * 2 + 1], 3);
}
send_tree(dyn_ltree, lcodes - 1); // literal tree
@@ -757,8 +725,7 @@ private void send_all_trees(int lcodes, int dcodes, int blcodes)
/// Send a literal or distance tree in compressed form, using the codes in
/// bl_tree.
///
- private void send_tree(short[] tree, int max_code)
- {
+ private void send_tree(short[] tree, int max_code) {
int n; // iterates over all tree elements
int prevlen = -1; // last emitted length
int curlen; // length of current code
@@ -767,56 +734,38 @@ private void send_tree(short[] tree, int max_code)
int max_count = 7; // max repeat count
int min_count = 4; // min repeat count
- if (nextlen == 0)
- {
+ if (nextlen == 0) {
max_count = 138; min_count = 3;
}
- for (n = 0; n <= max_code; n++)
- {
+ for (n = 0; n <= max_code; n++) {
curlen = nextlen; nextlen = tree[(n + 1) * 2 + 1];
- if (++count < max_count && curlen == nextlen)
- {
+ if (++count < max_count && curlen == nextlen) {
continue;
- }
- else if (count < min_count)
- {
- do
- {
+ } else if (count < min_count) {
+ do {
send_code(curlen, bl_tree);
}
while (--count != 0);
- }
- else if (curlen != 0)
- {
- if (curlen != prevlen)
- {
+ } else if (curlen != 0) {
+ if (curlen != prevlen) {
send_code(curlen, bl_tree); count--;
}
send_code(REP_3_6, bl_tree);
send_bits(count - 3, 2);
- }
- else if (count <= 10)
- {
+ } else if (count <= 10) {
send_code(REPZ_3_10, bl_tree);
send_bits(count - 3, 3);
- }
- else
- {
+ } else {
send_code(REPZ_11_138, bl_tree);
send_bits(count - 11, 7);
}
count = 0; prevlen = curlen;
- if (nextlen == 0)
- {
+ if (nextlen == 0) {
max_count = 138; min_count = 3;
- }
- else if (curlen == nextlen)
- {
+ } else if (curlen == nextlen) {
max_count = 6; min_count = 3;
- }
- else
- {
+ } else {
max_count = 7; min_count = 4;
}
}
@@ -826,8 +775,7 @@ private void send_tree(short[] tree, int max_code)
/// Output a byte on the stream.
/// IN assertion: there is enough room in Pending_buf.
///
- private void put_byte(byte[] p, int start, int len)
- {
+ private void put_byte(byte[] p, int start, int len) {
Array.Copy(p, start, Pending_buf, Pending, len);
Pending += len;
}
@@ -835,42 +783,34 @@ private void put_byte(byte[] p, int start, int len)
///
/// Adds a byte to the buffer
///
- private void put_byte(byte c)
- {
+ private void put_byte(byte c) {
Pending_buf[Pending++] = c;
}
- private void put_short(int w)
- {
+ private void put_short(int w) {
put_byte((byte)(w));
put_byte((byte)(ZLibUtil.URShift(w, 8)));
}
- private void putShortMSB(int b)
- {
+ private void putShortMSB(int b) {
put_byte((byte)(b >> 8));
put_byte((byte)(b));
}
- private void send_code(int c, short[] tree)
- {
+ private void send_code(int c, short[] tree) {
send_bits((tree[c * 2] & 0xffff), (tree[c * 2 + 1] & 0xffff));
}
- private void send_bits(int value_Renamed, int length)
- {
+ private void send_bits(int value_Renamed, int length) {
int len = length;
- if (bi_valid > (int)Buf_size - len)
- {
+ if (bi_valid > (int)Buf_size - len) {
int val = value_Renamed;
// bi_buf |= (val << bi_valid);
bi_buf = (short)((ushort)bi_buf | (ushort)(((val << bi_valid) & 0xffff)));
put_short(bi_buf);
bi_buf = (short)(ZLibUtil.URShift(val, (Buf_size - bi_valid)));
bi_valid += len - Buf_size;
- }
- else
- {
+ } else {
// bi_buf |= (value) << bi_valid;
bi_buf = (short)((ushort)bi_buf | (ushort)((((value_Renamed) << bi_valid) & 0xffff)));
bi_valid += len;
@@ -888,8 +828,7 @@ private void send_bits(int value_Renamed, int length)
/// To simplify the code, we assume the worst case of last real code encoded
/// on one bit only.
///
- private void _tr_align()
- {
+ private void _tr_align() {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
@@ -899,8 +838,7 @@ private void _tr_align()
// (10 - bi_valid) bits. The lookahead for the last real code (before
// the EOB of the previous block) was thus at least one plus the length
// of the EOB plus what we have just sent of the empty static block.
- if (1 + last_eob_len + 10 - bi_valid < 9)
- {
+ if (1 + last_eob_len + 10 - bi_valid < 9) {
send_bits(STATIC_TREES << 1, 3);
send_code(END_BLOCK, StaticTree.static_ltree);
bi_flush();
@@ -912,21 +850,17 @@ private void _tr_align()
/// Save the match info and tally the frequency counts. Return true if
/// the current block must be flushed.
///
- private bool _tr_tally(int dist, int lc)
- {
+ private bool _tr_tally(int dist, int lc) {
Pending_buf[d_buf + last_lit * 2] = (byte)(ZLibUtil.URShift(dist, 8));
Pending_buf[d_buf + last_lit * 2 + 1] = (byte)dist;
Pending_buf[l_buf + last_lit] = (byte)lc; last_lit++;
- if (dist == 0)
- {
+ if (dist == 0) {
// lc is the unmatched char
dyn_ltree[lc * 2]++;
- }
- else
- {
+ } else {
matches++;
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
@@ -934,14 +868,12 @@ private bool _tr_tally(int dist, int lc)
dyn_dtree[Tree.d_code(dist) * 2]++;
}
- if ((last_lit & 0x1fff) == 0 && level > 2)
- {
+ if ((last_lit & 0x1fff) == 0 && level > 2) {
// Compute an upper bound for the compressed length
int out_length = last_lit * 8;
int in_length = strstart - block_start;
int dcode;
- for (dcode = 0; dcode < D_CODES; dcode++)
- {
+ for (dcode = 0; dcode < D_CODES; dcode++) {
out_length = (int)(out_length + (int)dyn_dtree[dcode * 2] * (5L + ZLibUtil.extra_dbits[dcode]));
}
out_length = ZLibUtil.URShift(out_length, 3);
@@ -958,34 +890,27 @@ private bool _tr_tally(int dist, int lc)
///
/// Send the block data compressed using the given Huffman trees
///
- private void compress_block(short[] ltree, short[] dtree)
- {
+ private void compress_block(short[] ltree, short[] dtree) {
int dist; // distance of matched string
int lc; // match length or unmatched char (if dist == 0)
int lx = 0; // running index in l_buf
int code; // the code to send
int extra; // number of extra bits to send
- if (last_lit != 0)
- {
- do
- {
+ if (last_lit != 0) {
+ do {
dist = ((Pending_buf[d_buf + lx * 2] << 8) & 0xff00) | (Pending_buf[d_buf + lx * 2 + 1] & 0xff);
lc = (Pending_buf[l_buf + lx]) & 0xff; lx++;
- if (dist == 0)
- {
+ if (dist == 0) {
send_code(lc, ltree); // send a literal byte
- }
- else
- {
+ } else {
// Here, lc is the match length - MIN_MATCH
code = ZLibUtil._length_code[lc];
send_code(code + LITERALS + 1, ltree); // send the length code
extra = ZLibUtil.extra_lbits[code];
- if (extra != 0)
- {
+ if (extra != 0) {
lc -= ZLibUtil.base_length[code];
send_bits(lc, extra); // send the extra length bits
}
@@ -994,8 +919,7 @@ private void compress_block(short[] ltree, short[] dtree)
send_code(code, dtree); // send the distance code
extra = ZLibUtil.extra_dbits[code];
- if (extra != 0)
- {
+ if (extra != 0) {
dist -= ZLibUtil.base_dist[code];
send_bits(dist, extra); // send the extra distance bits
}
@@ -1016,21 +940,17 @@ private void compress_block(short[] ltree, short[] dtree)
/// IN assertion: the fields freq of dyn_ltree are set and the total of all
/// frequencies does not exceed 64K (to fit in an int on 16 bit machines).
///
- private void set_data_type()
- {
+ private void set_data_type() {
int n = 0;
int ascii_freq = 0;
int bin_freq = 0;
- while (n < 7)
- {
+ while (n < 7) {
bin_freq += dyn_ltree[n * 2]; n++;
}
- while (n < 128)
- {
+ while (n < 128) {
ascii_freq += dyn_ltree[n * 2]; n++;
}
- while (n < LITERALS)
- {
+ while (n < LITERALS) {
bin_freq += dyn_ltree[n * 2]; n++;
}
data_type = (bin_freq > (ZLibUtil.URShift(ascii_freq, 2)) ? BlockType.Z_BINARY : BlockType.Z_ASCII);
@@ -1039,16 +959,12 @@ private void set_data_type()
///
/// Flush the bit buffer, keeping at most 7 bits in it.
///
- private void bi_flush()
- {
- if (bi_valid == 16)
- {
+ private void bi_flush() {
+ if (bi_valid == 16) {
put_short(bi_buf);
bi_buf = 0;
bi_valid = 0;
- }
- else if (bi_valid >= 8)
- {
+ } else if (bi_valid >= 8) {
put_byte((byte)bi_buf);
bi_buf = (short)(ZLibUtil.URShift(bi_buf, 8));
bi_valid -= 8;
@@ -1058,14 +974,10 @@ private void bi_flush()
///
/// Flush the bit buffer and align the output on a byte boundary
///
- private void bi_windup()
- {
- if (bi_valid > 8)
- {
+ private void bi_windup() {
+ if (bi_valid > 8) {
put_short(bi_buf);
- }
- else if (bi_valid > 0)
- {
+ } else if (bi_valid > 0) {
put_byte((byte)bi_buf);
}
bi_buf = 0;
@@ -1076,14 +988,12 @@ private void bi_windup()
/// Copy a stored block, storing first the length and its
/// one's complement if requested.
///
- private void copy_block(int buf, int len, bool header)
- {
+ private void copy_block(int buf, int len, bool header) {
bi_windup(); // align on byte boundary
last_eob_len = 8; // enough lookahead for inflate
- if (header)
- {
+ if (header) {
put_short((short)len);
put_short((short)~len);
}
@@ -1094,8 +1004,7 @@ private void copy_block(int buf, int len, bool header)
///
/// Flushes block
///
- private void flush_block_only(bool eof)
- {
+ private void flush_block_only(bool eof) {
_tr_flush_block(block_start >= 0 ? block_start : -1, strstart - block_start, eof);
block_start = strstart;
strm.FlushPending();
@@ -1110,25 +1019,21 @@ private void flush_block_only(bool eof)
/// NOTE: this function should be optimized to avoid extra copying from
/// Window to Pending_buf.
///
- private int deflate_stored(int flush)
- {
+ private int deflate_stored(int flush) {
// Stored blocks are limited to 0xffff bytes, Pending_buf is limited
// to pending_buf_size, and each stored block has a 5 byte header:
int max_block_size = 0xffff;
int max_start;
- if (max_block_size > pending_buf_size - 5)
- {
+ if (max_block_size > pending_buf_size - 5) {
max_block_size = pending_buf_size - 5;
}
// Copy as much as possible from input to output:
- while (true)
- {
+ while (true) {
// Fill the Window as much as possible:
- if (lookahead <= 1)
- {
+ if (lookahead <= 1) {
fill_window();
if (lookahead == 0 && flush == (int)FlushStrategy.Z_NO_FLUSH)
return NeedMore;
@@ -1141,8 +1046,7 @@ private int deflate_stored(int flush)
// Emit a stored block if Pending_buf will be full:
max_start = block_start + max_block_size;
- if (strstart == 0 || strstart >= max_start)
- {
+ if (strstart == 0 || strstart >= max_start) {
// strstart == 0 is possible when wraparound on 16-bit machine
lookahead = (int)(strstart - max_start);
strstart = (int)max_start;
@@ -1154,8 +1058,7 @@ private int deflate_stored(int flush)
// Flush if we may have to slide, otherwise block_start may become
// negative and the data will be gone:
- if (strstart - block_start >= w_size - MIN_LOOKAHEAD)
- {
+ if (strstart - block_start >= w_size - MIN_LOOKAHEAD) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
@@ -1172,8 +1075,7 @@ private int deflate_stored(int flush)
///
/// Send a stored block
///
- private void _tr_stored_block(int buf, int stored_len, bool eof)
- {
+ private void _tr_stored_block(int buf, int stored_len, bool eof) {
send_bits((STORED_BLOCK << 1) + (eof ? 1 : 0), 3); // send block type
copy_block(buf, stored_len, true); // with header
}
@@ -1182,14 +1084,12 @@ private void _tr_stored_block(int buf, int stored_len, bool eof)
/// Determine the best encoding for the current block: dynamic trees, static
/// trees or store, and output the encoded block to the zip file.
///
- private void _tr_flush_block(int buf, int stored_len, bool eof)
- {
+ private void _tr_flush_block(int buf, int stored_len, bool eof) {
int opt_lenb, static_lenb; // opt_len and static_len in bytes
int max_blindex = 0; // index of last bit length code of non zero freq
// Build the Huffman trees unless a stored block is forced
- if (level > 0)
- {
+ if (level > 0) {
// Check if the file is ascii or binary
if (data_type == BlockType.Z_UNKNOWN)
set_data_type();
@@ -1212,14 +1112,11 @@ private void _tr_flush_block(int buf, int stored_len, bool eof)
if (static_lenb <= opt_lenb)
opt_lenb = static_lenb;
- }
- else
- {
+ } else {
opt_lenb = static_lenb = stored_len + 5; // force a stored block
}
- if (stored_len + 4 <= opt_lenb && buf != -1)
- {
+ if (stored_len + 4 <= opt_lenb && buf != -1) {
// 4: two words for the lengths
// The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
// Otherwise we can't have processed more than WSIZE input bytes since
@@ -1227,14 +1124,10 @@ private void _tr_flush_block(int buf, int stored_len, bool eof)
// successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
// transform a block into a stored block.
_tr_stored_block(buf, stored_len, eof);
- }
- else if (static_lenb == opt_lenb)
- {
+ } else if (static_lenb == opt_lenb) {
send_bits((STATIC_TREES << 1) + (eof ? 1 : 0), 3);
compress_block(StaticTree.static_ltree, StaticTree.static_dtree);
- }
- else
- {
+ } else {
send_bits((DYN_TREES << 1) + (eof ? 1 : 0), 3);
send_all_trees(l_desc.MaxCode + 1, d_desc.MaxCode + 1, max_blindex + 1);
compress_block(dyn_ltree, dyn_dtree);
@@ -1245,8 +1138,7 @@ private void _tr_flush_block(int buf, int stored_len, bool eof)
init_block();
- if (eof)
- {
+ if (eof) {
bi_windup();
}
}
@@ -1261,32 +1153,25 @@ private void _tr_flush_block(int buf, int stored_len, bool eof)
/// performed for at least two bytes (required for the zip translate_eol
/// option -- not supported here).
///
- private void fill_window()
- {
+ private void fill_window() {
int n, m;
int p;
int more; // Amount of free space at the End of the Window.
- do
- {
+ do {
more = (window_size - lookahead - strstart);
// Deal with !@#$% 64K limit:
- if (more == 0 && strstart == 0 && lookahead == 0)
- {
+ if (more == 0 && strstart == 0 && lookahead == 0) {
more = w_size;
- }
- else if (more == -1)
- {
+ } else if (more == -1) {
// Very unlikely, but possible on 16 bit machine if strstart == 0
// and lookahead == 1 (input done one byte at time)
more--;
// If the Window is almost full and there is insufficient lookahead,
// move the upper half to the lower one to make room in the upper half.
- }
- else if (strstart >= w_size + w_size - MIN_LOOKAHEAD)
- {
+ } else if (strstart >= w_size + w_size - MIN_LOOKAHEAD) {
Array.Copy(window, w_size, window, 0, w_size);
match_start -= w_size;
strstart -= w_size; // we now have strstart >= MAX_DIST
@@ -1300,8 +1185,7 @@ private void fill_window()
n = hash_size;
p = n;
- do
- {
+ do {
m = (head[--p] & 0xffff);
head[p] = (short)(m >= w_size ? (m - w_size) : 0);
//head[p] = (m >= w_size?(short) (m - w_size):0);
@@ -1310,8 +1194,7 @@ private void fill_window()
n = w_size;
p = n;
- do
- {
+ do {
m = (prev[--p] & 0xffff);
prev[p] = (short)(m >= w_size ? (m - w_size) : 0);
//prev[p] = (m >= w_size?(short) (m - w_size):0);
@@ -1340,8 +1223,7 @@ private void fill_window()
lookahead += n;
// Initialize the hash value now that we have some input:
- if (lookahead >= MIN_MATCH)
- {
+ if (lookahead >= MIN_MATCH) {
ins_h = window[strstart] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[strstart + 1] & 0xff)) & hash_mask;
}
@@ -1358,23 +1240,19 @@ private void fill_window()
/// new strings in the dictionary only for unmatched strings or for short
/// matches. It is used only for the fast compression options.
///
- private int deflate_fast(int flush)
- {
+ private int deflate_fast(int flush) {
// short hash_head = 0; // head of the hash chain
int hash_head = 0; // head of the hash chain
bool bflush; // set if current block must be flushed
- while (true)
- {
+ while (true) {
// Make sure that we always have enough lookahead, except
// at the End of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
- if (lookahead < MIN_LOOKAHEAD)
- {
+ if (lookahead < MIN_LOOKAHEAD) {
fill_window();
- if (lookahead < MIN_LOOKAHEAD && flush == (int)FlushStrategy.Z_NO_FLUSH)
- {
+ if (lookahead < MIN_LOOKAHEAD && flush == (int)FlushStrategy.Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead == 0)
@@ -1383,8 +1261,7 @@ private int deflate_fast(int flush)
// Insert the string Window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
- if (lookahead >= MIN_MATCH)
- {
+ if (lookahead >= MIN_MATCH) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
@@ -1396,19 +1273,16 @@ private int deflate_fast(int flush)
// Find the longest match, discarding those <= prev_length.
// At this point we have always match_length < MIN_MATCH
- if (hash_head != 0L && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD)
- {
+ if (hash_head != 0L && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of Window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
- if (strategy != CompressionStrategy.Z_HUFFMAN_ONLY)
- {
+ if (strategy != CompressionStrategy.Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
}
- if (match_length >= MIN_MATCH)
- {
+ if (match_length >= MIN_MATCH) {
// check_match(strstart, match_start, match_length);
bflush = _tr_tally(strstart - match_start, match_length - MIN_MATCH);
@@ -1417,11 +1291,9 @@ private int deflate_fast(int flush)
// Insert new strings in the hash table only if the match length
// is not too large. This saves time but degrades compression.
- if (match_length <= max_lazy_match && lookahead >= MIN_MATCH)
- {
+ if (match_length <= max_lazy_match && lookahead >= MIN_MATCH) {
match_length--; // string at strstart already in hash table
- do
- {
+ do {
strstart++;
ins_h = ((ins_h << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
@@ -1435,9 +1307,7 @@ private int deflate_fast(int flush)
}
while (--match_length != 0);
strstart++;
- }
- else
- {
+ } else {
strstart += match_length;
match_length = 0;
ins_h = window[strstart] & 0xff;
@@ -1446,17 +1316,14 @@ private int deflate_fast(int flush)
// If lookahead < MIN_MATCH, ins_h is garbage, but it does not
// matter since it will be recomputed at next deflate call.
}
- }
- else
- {
+ } else {
// No match, output a literal byte
bflush = _tr_tally(0, window[strstart] & 0xff);
lookahead--;
strstart++;
}
- if (bflush)
- {
+ if (bflush) {
flush_block_only(false);
if (strm.avail_out == 0)
@@ -1465,8 +1332,7 @@ private int deflate_fast(int flush)
}
flush_block_only(flush == (int)FlushStrategy.Z_FINISH);
- if (strm.avail_out == 0)
- {
+ if (strm.avail_out == 0) {
if (flush == (int)FlushStrategy.Z_FINISH)
return FinishStarted;
else
@@ -1480,25 +1346,21 @@ private int deflate_fast(int flush)
/// evaluation for matches: a match is finally adopted only if there is
/// no better match at the next Window position.
///
- private int deflate_slow(int flush)
- {
+ private int deflate_slow(int flush) {
// short hash_head = 0; // head of hash chain
int hash_head = 0; // head of hash chain
bool bflush; // set if current block must be flushed
// Process the input block.
- while (true)
- {
+ while (true) {
// Make sure that we always have enough lookahead, except
// at the End of the input file. We need MAX_MATCH bytes
// for the next match, plus MIN_MATCH bytes to insert the
// string following the next match.
- if (lookahead < MIN_LOOKAHEAD)
- {
+ if (lookahead < MIN_LOOKAHEAD) {
fill_window();
- if (lookahead < MIN_LOOKAHEAD && flush == (int)FlushStrategy.Z_NO_FLUSH)
- {
+ if (lookahead < MIN_LOOKAHEAD && flush == (int)FlushStrategy.Z_NO_FLUSH) {
return NeedMore;
}
if (lookahead == 0)
@@ -1508,8 +1370,7 @@ private int deflate_slow(int flush)
// Insert the string Window[strstart .. strstart+2] in the
// dictionary, and set hash_head to the head of the hash chain:
- if (lookahead >= MIN_MATCH)
- {
+ if (lookahead >= MIN_MATCH) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
// prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
@@ -1521,20 +1382,17 @@ private int deflate_slow(int flush)
prev_length = match_length; prev_match = match_start;
match_length = MIN_MATCH - 1;
- if (hash_head != 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD)
- {
+ if (hash_head != 0 && prev_length < max_lazy_match && ((strstart - hash_head) & 0xffff) <= w_size - MIN_LOOKAHEAD) {
// To simplify the code, we prevent matches with the string
// of Window index 0 (in particular we have to avoid a match
// of the string with itself at the start of the input file).
- if (strategy != CompressionStrategy.Z_HUFFMAN_ONLY)
- {
+ if (strategy != CompressionStrategy.Z_HUFFMAN_ONLY) {
match_length = longest_match(hash_head);
}
// longest_match() sets match_start
- if (match_length <= 5 && (strategy == CompressionStrategy.Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096)))
- {
+ if (match_length <= 5 && (strategy == CompressionStrategy.Z_FILTERED || (match_length == MIN_MATCH && strstart - match_start > 4096))) {
// If prev_match is also MIN_MATCH, match_start is garbage
// but we will ignore the current match anyway.
@@ -1544,8 +1402,7 @@ private int deflate_slow(int flush)
// If there was a match at the previous step and the current
// match is not better, output the previous match:
- if (prev_length >= MIN_MATCH && match_length <= prev_length)
- {
+ if (prev_length >= MIN_MATCH && match_length <= prev_length) {
int max_insert = strstart + lookahead - MIN_MATCH;
// Do not insert strings in hash table beyond this.
@@ -1559,10 +1416,8 @@ private int deflate_slow(int flush)
// the hash table.
lookahead -= (prev_length - 1);
prev_length -= 2;
- do
- {
- if (++strstart <= max_insert)
- {
+ do {
+ if (++strstart <= max_insert) {
ins_h = (((ins_h) << hash_shift) ^ (window[(strstart) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
//prev[strstart&w_mask]=hash_head=head[ins_h];
hash_head = (head[ins_h] & 0xffff);
@@ -1575,15 +1430,12 @@ private int deflate_slow(int flush)
match_length = MIN_MATCH - 1;
strstart++;
- if (bflush)
- {
+ if (bflush) {
flush_block_only(false);
if (strm.avail_out == 0)
return NeedMore;
}
- }
- else if (match_available != 0)
- {
+ } else if (match_available != 0) {
// If there was no match at the previous position, output a
// single literal. If there was a match but the current match
@@ -1591,17 +1443,14 @@ private int deflate_slow(int flush)
bflush = _tr_tally(0, window[strstart - 1] & 0xff);
- if (bflush)
- {
+ if (bflush) {
flush_block_only(false);
}
strstart++;
lookahead--;
if (strm.avail_out == 0)
return NeedMore;
- }
- else
- {
+ } else {
// There is no previous match to compare with, wait for
// the next step to decide.
@@ -1611,15 +1460,13 @@ private int deflate_slow(int flush)
}
}
- if (match_available != 0)
- {
+ if (match_available != 0) {
bflush = _tr_tally(0, window[strstart - 1] & 0xff);
match_available = 0;
}
flush_block_only(flush == (int)FlushStrategy.Z_FINISH);
- if (strm.avail_out == 0)
- {
+ if (strm.avail_out == 0) {
if (flush == (int)FlushStrategy.Z_FINISH)
return FinishStarted;
@@ -1632,8 +1479,7 @@ private int deflate_slow(int flush)
///
/// Finds the longest matching data part
///
- private int longest_match(int cur_match)
- {
+ private int longest_match(int cur_match) {
int chain_length = max_chain_length; // max hash chain length
int scan = strstart; // current string
int match; // matched string
@@ -1655,8 +1501,7 @@ private int longest_match(int cur_match)
// It is easy to get rid of this optimization if necessary.
// Do not waste too much time if we already have a good match:
- if (prev_length >= good_match)
- {
+ if (prev_length >= good_match) {
chain_length >>= 2;
}
@@ -1665,8 +1510,7 @@ private int longest_match(int cur_match)
if (nice_match > lookahead)
nice_match = lookahead;
- do
- {
+ do {
match = cur_match;
// Skip to next match if the match length cannot increase
@@ -1683,16 +1527,14 @@ private int longest_match(int cur_match)
// We check for insufficient lookahead only every 8th comparison;
// the 256th check will be made at strstart+258.
- do
- {
+ do {
}
while (window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && window[++scan] == window[++match] && scan < strend);
len = MAX_MATCH - (int)(strend - scan);
scan = strend - MAX_MATCH;
- if (len > best_len)
- {
+ if (len > best_len) {
match_start = cur_match;
best_len = len;
if (len >= nice_match)
@@ -1715,8 +1557,7 @@ private int longest_match(int cur_match)
/// Compression level
/// Window bits
/// A result code
- internal int DeflateInit(ZStream strm, int level, int bits)
- {
+ internal int DeflateInit(ZStream strm, int level, int bits) {
return DeflateInit2(strm, level, bits, DEF_MEM_LEVEL, CompressionStrategy.Z_DEFAULT_STRATEGY);
}
@@ -1726,8 +1567,7 @@ internal int DeflateInit(ZStream strm, int level, int bits)
/// ZStream object
/// Compression level
/// Operation result result code
- internal int DeflateInit(ZStream strm, int level)
- {
+ internal int DeflateInit(ZStream strm, int level) {
return DeflateInit(strm, level, ZLibUtil.MAX_WBITS);
}
@@ -1740,8 +1580,7 @@ internal int DeflateInit(ZStream strm, int level)
/// Memory level
/// Compression strategy
/// Operation result code
- internal int DeflateInit2(ZStream strm, int level, int windowBits, int memLevel, CompressionStrategy strategy)
- {
+ internal int DeflateInit2(ZStream strm, int level, int windowBits, int memLevel, CompressionStrategy strategy) {
int noheader = 0;
strm.msg = null;
@@ -1749,15 +1588,13 @@ internal int DeflateInit2(ZStream strm, int level, int windowBits, int memLevel,
if (level == Z_DEFAULT_COMPRESSION)
level = 6;
- if (windowBits < 0)
- {
+ if (windowBits < 0) {
// undocumented feature: suppress zlib header
noheader = 1;
windowBits = -windowBits;
}
- if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > CompressionStrategy.Z_HUFFMAN_ONLY)
- {
+ if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > CompressionStrategy.Z_HUFFMAN_ONLY) {
return (int)ZLibResultCode.Z_STREAM_ERROR;
}
@@ -1798,8 +1635,7 @@ internal int DeflateInit2(ZStream strm, int level, int windowBits, int memLevel,
///
/// Resets the current state of deflate object
///
- internal int deflateReset(ZStream strm)
- {
+ internal int deflateReset(ZStream strm) {
strm.total_in = strm.total_out = 0;
strm.msg = null; //
strm.Data_type = BlockType.Z_UNKNOWN;
@@ -1807,8 +1643,7 @@ internal int deflateReset(ZStream strm)
Pending = 0;
Pending_out = 0;
- if (NoHeader < 0)
- {
+ if (NoHeader < 0) {
NoHeader = 0; // was set to -1 by deflate(..., Z_FINISH);
}
status = (NoHeader != 0) ? DeflateState.BUSY_STATE : DeflateState.INIT_STATE;
@@ -1825,10 +1660,8 @@ internal int deflateReset(ZStream strm)
///
/// Finish compression with deflate algorithm
///
- internal int deflateEnd()
- {
- if (status != DeflateState.INIT_STATE && status != DeflateState.BUSY_STATE && status != DeflateState.FINISH_STATE)
- {
+ internal int deflateEnd() {
+ if (status != DeflateState.INIT_STATE && status != DeflateState.BUSY_STATE && status != DeflateState.FINISH_STATE) {
return (int)ZLibResultCode.Z_STREAM_ERROR;
}
// Deallocate in reverse order of allocations:
@@ -1843,27 +1676,22 @@ internal int deflateEnd()
///
/// Sets deflate algorithm parameters
///
- internal int deflateParams(ZStream strm, int level, CompressionStrategy strategy)
- {
+ internal int deflateParams(ZStream strm, int level, CompressionStrategy strategy) {
int err = (int)ZLibResultCode.Z_OK;
- if (level == Z_DEFAULT_COMPRESSION)
- {
+ if (level == Z_DEFAULT_COMPRESSION) {
level = 6;
}
- if (level < 0 || level > 9 || strategy < 0 || strategy > CompressionStrategy.Z_HUFFMAN_ONLY)
- {
+ if (level < 0 || level > 9 || strategy < 0 || strategy > CompressionStrategy.Z_HUFFMAN_ONLY) {
return (int)ZLibResultCode.Z_STREAM_ERROR;
}
- if (config_table[this.level].func != config_table[level].func && strm.total_in != 0)
- {
+ if (config_table[this.level].func != config_table[level].func && strm.total_in != 0) {
// Flush the last buffer:
err = strm.deflate(FlushStrategy.Z_PARTIAL_FLUSH);
}
- if (this.level != level)
- {
+ if (this.level != level) {
this.level = level;
max_lazy_match = config_table[this.level].max_lazy;
good_match = config_table[this.level].good_length;
@@ -1877,8 +1705,7 @@ internal int deflateParams(ZStream strm, int level, CompressionStrategy strategy
///
/// Sets deflate dictionary
///
- internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength)
- {
+ internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLength) {
int length = dictLength;
int index = 0;
@@ -1889,8 +1716,7 @@ internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLengt
if (length < MIN_MATCH)
return (int)ZLibResultCode.Z_OK;
- if (length > w_size - MIN_LOOKAHEAD)
- {
+ if (length > w_size - MIN_LOOKAHEAD) {
length = w_size - MIN_LOOKAHEAD;
index = dictLength - length; // use the tail of the dictionary
}
@@ -1905,8 +1731,7 @@ internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLengt
ins_h = window[0] & 0xff;
ins_h = (((ins_h) << hash_shift) ^ (window[1] & 0xff)) & hash_mask;
- for (int n = 0; n <= length - MIN_MATCH; n++)
- {
+ for (int n = 0; n <= length - MIN_MATCH; n++) {
ins_h = (((ins_h) << hash_shift) ^ (window[(n) + (MIN_MATCH - 1)] & 0xff)) & hash_mask;
prev[n & w_mask] = head[ins_h];
head[ins_h] = (short)n;
@@ -1917,22 +1742,18 @@ internal int deflateSetDictionary(ZStream strm, byte[] dictionary, int dictLengt
///
/// Performs data compression with the deflate algorithm
///
- internal int deflate(ZStream strm, FlushStrategy f)
- {
+ internal int deflate(ZStream strm, FlushStrategy f) {
int internalFlush = (int)f;
- if (internalFlush > (int)FlushStrategy.Z_FINISH || internalFlush < 0)
- {
+ if (internalFlush > (int)FlushStrategy.Z_FINISH || internalFlush < 0) {
return (int)ZLibResultCode.Z_STREAM_ERROR;
}
- if (strm.next_out == null || (strm.next_in == null && strm.avail_in != 0) || (status == DeflateState.FINISH_STATE && internalFlush != (int)FlushStrategy.Z_FINISH))
- {
+ if (strm.next_out == null || (strm.next_in == null && strm.avail_in != 0) || (status == DeflateState.FINISH_STATE && internalFlush != (int)FlushStrategy.Z_FINISH)) {
strm.msg = ZLibUtil.z_errmsg[(int)ZLibResultCode.Z_NEED_DICT - ((int)ZLibResultCode.Z_STREAM_ERROR)];
return (int)ZLibResultCode.Z_STREAM_ERROR;
}
- if (strm.avail_out == 0)
- {
+ if (strm.avail_out == 0) {
strm.msg = ZLibUtil.z_errmsg[(int)ZLibResultCode.Z_NEED_DICT - ((int)ZLibResultCode.Z_BUF_ERROR)];
return (int)ZLibResultCode.Z_BUF_ERROR;
}
@@ -1942,8 +1763,7 @@ internal int deflate(ZStream strm, FlushStrategy f)
last_flush = internalFlush;
// Write the zlib header
- if (status == DeflateState.INIT_STATE)
- {
+ if (status == DeflateState.INIT_STATE) {
int header = (Z_DEFLATED + ((w_bits - 8) << 4)) << 8;
int level_flags = (level > 0) ? ((level - 1) & 0xff) >> 1 : 0;
@@ -1959,8 +1779,7 @@ internal int deflate(ZStream strm, FlushStrategy f)
// Save the adler32 of the preset dictionary:
- if (strstart != 0)
- {
+ if (strstart != 0) {
putShortMSB((int)(ZLibUtil.URShift(strm.adler, 16)));
putShortMSB((int)(strm.adler & 0xffff));
}
@@ -1968,11 +1787,9 @@ internal int deflate(ZStream strm, FlushStrategy f)
}
// Flush as much pending output as possible
- if (Pending != 0)
- {
+ if (Pending != 0) {
strm.FlushPending();
- if (strm.avail_out == 0)
- {
+ if (strm.avail_out == 0) {
//System.out.println(" _avail_out==0");
// Since _avail_out is 0, deflate will be called again with
// more output space, but possibly with both pending and
@@ -1986,90 +1803,76 @@ internal int deflate(ZStream strm, FlushStrategy f)
// Make sure there is something to do and avoid duplicate consecutive
// flushes. For repeated and useless calls with Z_FINISH, we keep
// returning (int)ZLibResultCode.Z_STREAM_END instead of Z_BUFF_ERROR.
- }
- else if (strm.avail_in == 0 && internalFlush <= old_flush && internalFlush != (int)FlushStrategy.Z_FINISH)
- {
+ } else if (strm.avail_in == 0 && internalFlush <= old_flush && internalFlush != (int)FlushStrategy.Z_FINISH) {
strm.msg = ZLibUtil.z_errmsg[(int)ZLibResultCode.Z_NEED_DICT - ((int)ZLibResultCode.Z_BUF_ERROR)];
return (int)ZLibResultCode.Z_BUF_ERROR;
}
// User must not provide more input after the first FINISH:
- if (status == DeflateState.FINISH_STATE && strm.avail_in != 0)
- {
+ if (status == DeflateState.FINISH_STATE && strm.avail_in != 0) {
strm.msg = ZLibUtil.z_errmsg[(int)ZLibResultCode.Z_NEED_DICT - ((int)ZLibResultCode.Z_BUF_ERROR)];
- return (int)ZLibResultCode.Z_BUF_ERROR;
- }
-
- // Start a new block or continue the current one.
- if (strm.avail_in != 0 || lookahead != 0 || (internalFlush != (int)FlushStrategy.Z_NO_FLUSH && status != DeflateState.FINISH_STATE))
- {
- int bstate = - 1;
- switch (config_table[level].func)
- {
-
- case STORED:
- bstate = deflate_stored(internalFlush);
- break;
-
- case FAST:
- bstate = deflate_fast(internalFlush);
- break;
-
- case SLOW:
- bstate = deflate_slow(internalFlush);
- break;
-
- default:
- break;
-
- }
-
- if (bstate == FinishStarted || bstate == FinishDone)
- {
- status = DeflateState.FINISH_STATE;
- }
- if (bstate == NeedMore || bstate == FinishStarted)
- {
- if (strm.avail_out == 0)
- {
- last_flush = -1; // avoid BUF_ERROR next call, see above
- }
- return (int)ZLibResultCode.Z_OK;
- // If internalFlush != Z_NO_FLUSH && _avail_out == 0, the next call
- // of deflate should use the same internalFlush parameter to make sure
- // that the internalFlush is complete. So we don't have to output an
- // empty block here, this will be done at next call. This also
- // ensures that for a very small output buffer, we emit at most
- // one empty block.
- }
-
- if (bstate == BlockDone)
- {
- if (internalFlush == (int)FlushStrategy.Z_PARTIAL_FLUSH)
- {
- _tr_align();
- }
- else
- {
- // FULL_FLUSH or SYNC_FLUSH
- _tr_stored_block(0, 0, false);
- // For a full internalFlush, this empty block will be recognized
- // as a special marker by inflate_sync().
- if (internalFlush == (int)FlushStrategy.Z_FULL_FLUSH)
- {
- for (int i = 0; i < hash_size; i++)
- // forget history
- head[i] = 0;
- }
- }
- strm.FlushPending();
- if (strm.avail_out == 0)
- {
- last_flush = -1; // avoid BUF_ERROR at next call, see above
- return (int)ZLibResultCode.Z_OK;
- }
- }
- }
+ return (int)ZLibResultCode.Z_BUF_ERROR;
+ }
+
+ // Start a new block or continue the current one.
+ if (strm.avail_in != 0 || lookahead != 0 || (internalFlush != (int)FlushStrategy.Z_NO_FLUSH && status != DeflateState.FINISH_STATE)) {
+ int bstate = -1;
+ switch (config_table[level].func) {
+
+ case STORED:
+ bstate = deflate_stored(internalFlush);
+ break;
+
+ case FAST:
+ bstate = deflate_fast(internalFlush);
+ break;
+
+ case SLOW:
+ bstate = deflate_slow(internalFlush);
+ break;
+
+ default:
+ break;
+
+ }
+
+ if (bstate == FinishStarted || bstate == FinishDone) {
+ status = DeflateState.FINISH_STATE;
+ }
+ if (bstate == NeedMore || bstate == FinishStarted) {
+ if (strm.avail_out == 0) {
+ last_flush = -1; // avoid BUF_ERROR next call, see above
+ }
+ return (int)ZLibResultCode.Z_OK;
+ // If internalFlush != Z_NO_FLUSH && _avail_out == 0, the next call
+ // of deflate should use the same internalFlush parameter to make sure
+ // that the internalFlush is complete. So we don't have to output an
+ // empty block here, this will be done at next call. This also
+ // ensures that for a very small output buffer, we emit at most
+ // one empty block.
+ }
+
+ if (bstate == BlockDone) {
+ if (internalFlush == (int)FlushStrategy.Z_PARTIAL_FLUSH) {
+ _tr_align();
+ } else {
+ // FULL_FLUSH or SYNC_FLUSH
+ _tr_stored_block(0, 0, false);
+ // For a full internalFlush, this empty block will be recognized
+ // as a special marker by inflate_sync().
+ if (internalFlush == (int)FlushStrategy.Z_FULL_FLUSH) {
+ for (int i = 0; i < hash_size; i++)
+ // forget history
+ head[i] = 0;
+ }
+ }
+ strm.FlushPending();
+ if (strm.avail_out == 0) {
+ last_flush = -1; // avoid BUF_ERROR at next call, see above
+ return (int)ZLibResultCode.Z_OK;
+ }
+ }
+ }
if (internalFlush != (int)FlushStrategy.Z_FINISH)
return (int)ZLibResultCode.Z_OK;
@@ -2077,13 +1880,13 @@ internal int deflate(ZStream strm, FlushStrategy f)
return (int)ZLibResultCode.Z_STREAM_END;
// Write the zlib trailer (adler32)
- putShortMSB((int) (ZLibUtil.URShift(strm.adler, 16)));
- putShortMSB((int) (strm.adler & 0xffff));
+ putShortMSB((int)(ZLibUtil.URShift(strm.adler, 16)));
+ putShortMSB((int)(strm.adler & 0xffff));
strm.FlushPending();
// If _avail_out is zero, the application will call deflate again
// to internalFlush the rest.
- NoHeader = - 1; // WritePos the trailer only once!
+ NoHeader = -1; // WritePos the trailer only once!
return Pending != 0 ? (int)ZLibResultCode.Z_OK : (int)ZLibResultCode.Z_STREAM_END;
}
@@ -2092,8 +1895,7 @@ internal int deflate(ZStream strm, FlushStrategy f)
///
/// Static constructor initializes config_table
///
- static Deflate()
- {
+ static Deflate() {
{
config_table = new Config[10];
// good lazy nice chain
@@ -2110,5 +1912,5 @@ static Deflate()
config_table[9] = new Config(32, 258, 258, 4096, SLOW);
}
}
- }
+ }
}
diff --git a/Src/IronPython.Modules/zlib/zlib.net/InfBlocks.cs b/Src/IronPython.Modules/zlib/zlib.net/InfBlocks.cs
index 3283c3e38..64f9fc02b 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/InfBlocks.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/InfBlocks.cs
@@ -43,11 +43,9 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
- internal enum InflateBlockMode
- {
+ internal enum InflateBlockMode {
TYPE = 0, // get type bits (3, including End bit)
LENS = 1, // get lengths for stored
STORED = 2, // processing stored block
@@ -60,8 +58,7 @@ internal enum InflateBlockMode
BAD = 9 // a data error--stuck here
}
- internal sealed class InfBlocks
- {
+ internal sealed class InfBlocks {
#region Fields
private const int MANY = 1440;
@@ -166,8 +163,7 @@ internal sealed class InfBlocks
#region Methods
- internal InfBlocks(ZStream z, bool needCheck, int w)
- {
+ internal InfBlocks(ZStream z, bool needCheck, int w) {
hufts = new int[MANY * 3];
Window = new byte[w];
End = w;
@@ -179,16 +175,13 @@ internal InfBlocks(ZStream z, bool needCheck, int w)
///
/// Resets this InfBlocks class instance
///
- internal void reset(ZStream z, long[] c)
- {
+ internal void reset(ZStream z, long[] c) {
if (c != null)
c[0] = check;
- if (mode == InflateBlockMode.BTREE || mode == InflateBlockMode.DTREE)
- {
+ if (mode == InflateBlockMode.BTREE || mode == InflateBlockMode.DTREE) {
blens = null;
}
- if (mode == InflateBlockMode.CODES)
- {
+ if (mode == InflateBlockMode.CODES) {
codes.free(z);
}
mode = InflateBlockMode.TYPE;
@@ -203,8 +196,7 @@ internal void reset(ZStream z, long[] c)
///
/// Block processing functions
///
- internal int proc(ZStream z, int r)
- {
+ internal int proc(ZStream z, int r) {
int t; // temporary storage
int b; // bit buffer
int k; // bits in bit buffer
@@ -222,21 +214,15 @@ internal int proc(ZStream z, int r)
}
// process input based on current state
- while (true)
- {
- switch (mode)
- {
+ while (true) {
+ switch (mode) {
case InflateBlockMode.TYPE:
- while (k < (3))
- {
- if (n != 0)
- {
+ while (k < (3)) {
+ if (n != 0) {
r = (int)ZLibResultCode.Z_OK;
- }
- else
- {
+ } else {
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
@@ -251,8 +237,7 @@ internal int proc(ZStream z, int r)
t = (int)(b & 7);
last = t & 1;
- switch (ZLibUtil.URShift(t, 1))
- {
+ switch (ZLibUtil.URShift(t, 1)) {
case 0: // stored
{
@@ -274,8 +259,7 @@ internal int proc(ZStream z, int r)
InfTree.inflate_trees_fixed(bl, bd, tl, td, z);
codes = new InfCodes(bl[0], bd[0], tl[0], td[0], z);
- }
- {
+ } {
b = ZLibUtil.URShift(b, (3)); k -= (3);
}
@@ -307,14 +291,10 @@ internal int proc(ZStream z, int r)
case InflateBlockMode.LENS:
- while (k < (32))
- {
- if (n != 0)
- {
+ while (k < (32)) {
+ if (n != 0) {
r = (int)ZLibResultCode.Z_OK;
- }
- else
- {
+ } else {
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
@@ -327,8 +307,7 @@ internal int proc(ZStream z, int r)
k += 8;
}
- if (((ZLibUtil.URShift((~b), 16)) & 0xffff) != (b & 0xffff))
- {
+ if (((ZLibUtil.URShift((~b), 16)) & 0xffff) != (b & 0xffff)) {
mode = InflateBlockMode.BAD;
z.msg = "invalid stored block lengths";
r = (int)ZLibResultCode.Z_DATA_ERROR;
@@ -344,31 +323,25 @@ internal int proc(ZStream z, int r)
break;
case InflateBlockMode.STORED:
- if (n == 0)
- {
+ if (n == 0) {
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
return inflate_flush(z, r);
}
- if (m == 0)
- {
- if (q == End && ReadPos != 0)
- {
+ if (m == 0) {
+ if (q == End && ReadPos != 0) {
q = 0; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
}
- if (m == 0)
- {
+ if (m == 0) {
WritePos = q;
r = inflate_flush(z, r);
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
- if (q == End && ReadPos != 0)
- {
+ if (q == End && ReadPos != 0) {
q = 0; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
}
- if (m == 0)
- {
+ if (m == 0) {
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
@@ -393,14 +366,10 @@ internal int proc(ZStream z, int r)
case InflateBlockMode.TABLE:
- while (k < (14))
- {
- if (n != 0)
- {
+ while (k < (14)) {
+ if (n != 0) {
r = (int)ZLibResultCode.Z_OK;
- }
- else
- {
+ } else {
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
@@ -414,8 +383,7 @@ internal int proc(ZStream z, int r)
}
table = t = (b & 0x3fff);
- if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
- {
+ if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29) {
mode = InflateBlockMode.BAD;
z.msg = "too many length or distance symbols";
r = (int)ZLibResultCode.Z_DATA_ERROR;
@@ -426,8 +394,7 @@ internal int proc(ZStream z, int r)
return inflate_flush(z, r);
}
t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
- blens = new int[t];
- {
+ blens = new int[t]; {
b = ZLibUtil.URShift(b, (14)); k -= (14);
}
@@ -436,16 +403,11 @@ internal int proc(ZStream z, int r)
goto case InflateBlockMode.BTREE;
case InflateBlockMode.BTREE:
- while (index < 4 + (ZLibUtil.URShift(table, 10)))
- {
- while (k < (3))
- {
- if (n != 0)
- {
+ while (index < 4 + (ZLibUtil.URShift(table, 10))) {
+ while (k < (3)) {
+ if (n != 0) {
r = (int)ZLibResultCode.Z_OK;
- }
- else
- {
+ } else {
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
@@ -465,18 +427,15 @@ internal int proc(ZStream z, int r)
}
}
- while (index < 19)
- {
+ while (index < 19) {
blens[ZLibUtil.border[index++]] = 0;
}
bb[0] = 7;
t = InfTree.inflate_trees_bits(blens, bb, tb, hufts, z);
- if (t != (int)ZLibResultCode.Z_OK)
- {
+ if (t != (int)ZLibResultCode.Z_OK) {
r = t;
- if (r == (int)ZLibResultCode.Z_DATA_ERROR)
- {
+ if (r == (int)ZLibResultCode.Z_DATA_ERROR) {
blens = null;
mode = InflateBlockMode.BAD;
}
@@ -492,11 +451,9 @@ internal int proc(ZStream z, int r)
goto case InflateBlockMode.DTREE;
case InflateBlockMode.DTREE:
- while (true)
- {
+ while (true) {
t = table;
- if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f)))
- {
+ if (!(index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))) {
break;
}
@@ -505,14 +462,10 @@ internal int proc(ZStream z, int r)
t = bb[0];
- while (k < (t))
- {
- if (n != 0)
- {
+ while (k < (t)) {
+ if (n != 0) {
r = (int)ZLibResultCode.Z_OK;
- }
- else
- {
+ } else {
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
@@ -528,25 +481,18 @@ internal int proc(ZStream z, int r)
t = hufts[(tb[0] + (b & ZLibUtil.inflate_mask[t])) * 3 + 1];
c = hufts[(tb[0] + (b & ZLibUtil.inflate_mask[t])) * 3 + 2];
- if (c < 16)
- {
+ if (c < 16) {
b = ZLibUtil.URShift(b, (t)); k -= (t);
blens[index++] = c;
- }
- else
- {
+ } else {
// c == 16..18
i = c == 18 ? 7 : c - 14;
j = c == 18 ? 11 : 3;
- while (k < (t + i))
- {
- if (n != 0)
- {
+ while (k < (t + i)) {
+ if (n != 0) {
r = (int)ZLibResultCode.Z_OK;
- }
- else
- {
+ } else {
BitB = b; BitK = k;
z.avail_in = n;
z.total_in += p - z.next_in_index; z.next_in_index = p;
@@ -567,8 +513,7 @@ internal int proc(ZStream z, int r)
i = index;
t = table;
- if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1))
- {
+ if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) || (c == 16 && i < 1)) {
blens = null;
mode = InflateBlockMode.BAD;
z.msg = "invalid bit length repeat";
@@ -581,8 +526,7 @@ internal int proc(ZStream z, int r)
}
c = c == 16 ? blens[i - 1] : 0;
- do
- {
+ do {
blens[i++] = c;
}
while (--j != 0);
@@ -590,8 +534,7 @@ internal int proc(ZStream z, int r)
}
}
- tb[0] = -1;
- {
+ tb[0] = -1; {
int[] bl = new int[1];
int[] bd = new int[1];
int[] tl = new int[1];
@@ -602,10 +545,8 @@ internal int proc(ZStream z, int r)
bd[0] = 6; // must be <= 9 for lookahead assumptions
t = table;
t = InfTree.inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f), blens, bl, bd, tl, td, hufts, z);
- if (t != (int)ZLibResultCode.Z_OK)
- {
- if (t == (int)ZLibResultCode.Z_DATA_ERROR)
- {
+ if (t != (int)ZLibResultCode.Z_OK) {
+ if (t == (int)ZLibResultCode.Z_DATA_ERROR) {
blens = null;
mode = InflateBlockMode.BAD;
}
@@ -628,8 +569,7 @@ internal int proc(ZStream z, int r)
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
- if ((r = codes.proc(this, z, r)) != (int)ZLibResultCode.Z_STREAM_END)
- {
+ if ((r = codes.proc(this, z, r)) != (int)ZLibResultCode.Z_STREAM_END) {
return inflate_flush(z, r);
}
r = (int)ZLibResultCode.Z_OK;
@@ -638,8 +578,7 @@ internal int proc(ZStream z, int r)
p = z.next_in_index; n = z.avail_in; b = BitB; k = BitK;
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
- if (last == 0)
- {
+ if (last == 0) {
mode = InflateBlockMode.TYPE;
break;
}
@@ -650,8 +589,7 @@ internal int proc(ZStream z, int r)
WritePos = q;
r = inflate_flush(z, r);
q = WritePos; m = (int)(q < ReadPos ? ReadPos - q - 1 : End - q);
- if (ReadPos != WritePos)
- {
+ if (ReadPos != WritePos) {
BitB = b; BitK = k;
z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
WritePos = q;
@@ -692,8 +630,7 @@ internal int proc(ZStream z, int r)
///
/// Frees inner buffers
///
- internal void free(ZStream z)
- {
+ internal void free(ZStream z) {
reset(z, null);
Window = null;
hufts = null;
@@ -704,8 +641,7 @@ internal void free(ZStream z)
/// Sets dictionary
///
- internal void set_dictionary(byte[] d, int start, int n)
- {
+ internal void set_dictionary(byte[] d, int start, int n) {
Array.Copy(d, start, Window, 0, n);
ReadPos = WritePos = n;
}
@@ -714,75 +650,72 @@ internal void set_dictionary(byte[] d, int start, int n)
/// Returns true if inflate is currently at the End of a block generated
/// by Z_SYNC_FLUSH or Z_FULL_FLUSH.
///
- internal int sync_point()
- {
+ internal int sync_point() {
return mode == InflateBlockMode.LENS ? 1 : 0;
}
///
/// copy as much as possible from the sliding Window to the output area
///
- internal int inflate_flush(ZStream z, int r)
- {
- // local copies of source and destination pointers
- int p = z.next_out_index;
- int q = ReadPos;
-
- // compute number of bytes to copy as far as End of Window
- int n = (int) ((q <= WritePos?WritePos:End) - q);
- if (n > z.avail_out)
- n = z.avail_out;
- if (n != 0 && r == (int)ZLibResultCode.Z_BUF_ERROR)
- r = (int)ZLibResultCode.Z_OK;
-
- // update counters
- z.avail_out -= n;
- z.total_out += n;
-
- // update check information
- if (needCheck)
- z.adler = check = Adler32.GetAdler32Checksum(check, Window, q, n);
-
- // copy as far as End of Window
- Array.Copy(Window, q, z.next_out, p, n);
- p += n;
- q += n;
-
- // see if more to copy at beginning of Window
- if (q == End)
- {
- // wrap pointers
- q = 0;
- if (WritePos == End)
- WritePos = 0;
-
- // compute bytes to copy
- n = WritePos - q;
- if (n > z.avail_out)
- n = z.avail_out;
- if (n != 0 && r == (int)ZLibResultCode.Z_BUF_ERROR)
- r = (int)ZLibResultCode.Z_OK;
-
- // update counters
- z.avail_out -= n;
- z.total_out += n;
-
- // update check information
- if (needCheck)
- z.adler = check = Adler32.GetAdler32Checksum(check, Window, q, n);
-
- // copy
- Array.Copy(Window, q, z.next_out, p, n);
- p += n;
- q += n;
- }
-
- // update pointers
- z.next_out_index = p;
- ReadPos = q;
-
- // done
- return r;
+ internal int inflate_flush(ZStream z, int r) {
+ // local copies of source and destination pointers
+ int p = z.next_out_index;
+ int q = ReadPos;
+
+ // compute number of bytes to copy as far as End of Window
+ int n = (int)((q <= WritePos ? WritePos : End) - q);
+ if (n > z.avail_out)
+ n = z.avail_out;
+ if (n != 0 && r == (int)ZLibResultCode.Z_BUF_ERROR)
+ r = (int)ZLibResultCode.Z_OK;
+
+ // update counters
+ z.avail_out -= n;
+ z.total_out += n;
+
+ // update check information
+ if (needCheck)
+ z.adler = check = Adler32.GetAdler32Checksum(check, Window, q, n);
+
+ // copy as far as End of Window
+ Array.Copy(Window, q, z.next_out, p, n);
+ p += n;
+ q += n;
+
+ // see if more to copy at beginning of Window
+ if (q == End) {
+ // wrap pointers
+ q = 0;
+ if (WritePos == End)
+ WritePos = 0;
+
+ // compute bytes to copy
+ n = WritePos - q;
+ if (n > z.avail_out)
+ n = z.avail_out;
+ if (n != 0 && r == (int)ZLibResultCode.Z_BUF_ERROR)
+ r = (int)ZLibResultCode.Z_OK;
+
+ // update counters
+ z.avail_out -= n;
+ z.total_out += n;
+
+ // update check information
+ if (needCheck)
+ z.adler = check = Adler32.GetAdler32Checksum(check, Window, q, n);
+
+ // copy
+ Array.Copy(Window, q, z.next_out, p, n);
+ p += n;
+ q += n;
+ }
+
+ // update pointers
+ z.next_out_index = p;
+ ReadPos = q;
+
+ // done
+ return r;
}
#endregion
diff --git a/Src/IronPython.Modules/zlib/zlib.net/InfCodes.cs b/Src/IronPython.Modules/zlib/zlib.net/InfCodes.cs
index 78700fcf8..79b7a371c 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/InfCodes.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/InfCodes.cs
@@ -43,32 +43,29 @@ EVEN IF ADVISED OF THE POSSIBI InflateCodesMode.LITY OF SUCH DAMAGE.
*/
using System;
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
///
/// Inflate codes mode
///
- internal enum InflateCodesMode
- {
- START = 0, // x: set up for InflateCodesMode.LEN
- LEN = 1, // i: get length/literal/eob next
- LENEXT = 2, // i: getting length extra (have base)
- DIST = 3, // i: get distance next
- DISTEXT = 4, // i: getting distance extra
- COPY = 5, // o: copying bytes in Window, waiting for space
- LIT = 6, // o: got literal, waiting for output space
- WASH = 7, // o: got eob, possibly still output waiting
- END = 8, // x: got eob and all data flushed
- BADCODE = 9 // x: got error
+ internal enum InflateCodesMode {
+ START = 0, // x: set up for InflateCodesMode.LEN
+ LEN = 1, // i: get length/literal/eob next
+ LENEXT = 2, // i: getting length extra (have base)
+ DIST = 3, // i: get distance next
+ DISTEXT = 4, // i: getting distance extra
+ COPY = 5, // o: copying bytes in Window, waiting for space
+ LIT = 6, // o: got literal, waiting for output space
+ WASH = 7, // o: got eob, possibly still output waiting
+ END = 8, // x: got eob and all data flushed
+ BADCODE = 9 // x: got error
}
///
/// This class is used by the InfBlocks class
///
- internal sealed class InfCodes
- {
-
+ internal sealed class InfCodes {
+
#region Fields
///
@@ -142,635 +139,563 @@ internal sealed class InfCodes
///
/// Constructor which takes literal, distance trees, corresponding bites decoded for branches, corresponding indexes and a ZStream object
///
- internal InfCodes(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, ZStream z)
- {
- mode = InflateCodesMode.START;
- lbits = (byte) bl;
- dbits = (byte) bd;
- ltree = tl;
- ltree_index = tl_index;
- dtree = td;
- dtree_index = td_index;
- }
+ internal InfCodes(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, ZStream z) {
+ mode = InflateCodesMode.START;
+ lbits = (byte)bl;
+ dbits = (byte)bd;
+ ltree = tl;
+ ltree_index = tl_index;
+ dtree = td;
+ dtree_index = td_index;
+ }
///
/// Constructor which takes literal, distance trees, corresponding bites decoded for branches and a ZStream object
///
- internal InfCodes(int bl, int bd, int[] tl, int[] td, ZStream z)
- {
- mode = InflateCodesMode.START;
- lbits = (byte) bl;
- dbits = (byte) bd;
- ltree = tl;
- ltree_index = 0;
- dtree = td;
- dtree_index = 0;
- }
-
+ internal InfCodes(int bl, int bd, int[] tl, int[] td, ZStream z) {
+ mode = InflateCodesMode.START;
+ lbits = (byte)bl;
+ dbits = (byte)bd;
+ ltree = tl;
+ ltree_index = 0;
+ dtree = td;
+ dtree_index = 0;
+ }
+
///
/// Block processing method
///
/// An instance of the InfBlocks class
/// A ZStream object
/// A result code
- internal int proc(InfBlocks s, ZStream z, int r)
- {
- int j; // temporary storage
- //int[] t; // temporary pointer
- int tindex; // temporary pointer
- int e; // extra bits or operation
- int b = 0; // bit buffer
- int k = 0; // bits in bit buffer
- int p = 0; // input data pointer
- int n; // bytes available there
- int q; // output Window WritePos pointer
- int m; // bytes to End of Window or ReadPos pointer
- int f; // pointer to copy strings from
-
- // copy input/output information to locals (UPDATE macro restores)
- p = z.next_in_index; n = z.avail_in; b = s.BitB; k = s.BitK;
- q = s.WritePos; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
-
- // process input and output based on current state
- while (true)
- {
- switch (mode)
- {
-
- // waiting for "i:"=input, "o:"=output, "x:"=nothing
- case InflateCodesMode.START: // x: set up for InflateCodesMode.LEN
- if (m >= 258 && n >= 10)
- {
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z);
-
- p = z.next_in_index; n = z.avail_in; b = s.BitB; k = s.BitK;
- q = s.WritePos; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
-
- if (r != (int)ZLibResultCode.Z_OK)
- {
- mode = r == (int)ZLibResultCode.Z_STREAM_END? InflateCodesMode.WASH: InflateCodesMode.BADCODE;
- break;
- }
- }
- need = lbits;
- tree = ltree;
- tree_index = ltree_index;
-
- mode = InflateCodesMode.LEN;
- goto case InflateCodesMode.LEN;
-
- case InflateCodesMode.LEN: // i: get length/literal/eob next
- j = need;
-
- while (k < (j))
- {
- if (n != 0)
- r = (int)ZLibResultCode.Z_OK;
- else
- {
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- n--;
- b |= (z.next_in[p++] & 0xff) << k;
- k += 8;
- }
-
- tindex = (tree_index + (b & ZLibUtil.inflate_mask[j])) * 3;
-
- b = ZLibUtil.URShift(b, (tree[tindex + 1]));
- k -= (tree[tindex + 1]);
-
- e = tree[tindex];
-
- if (e == 0)
- {
- // literal
- lit = tree[tindex + 2];
- mode = InflateCodesMode.LIT;
- break;
- }
- if ((e & 16) != 0)
- {
- // length
- get_Renamed = e & 15;
- count = tree[tindex + 2];
- mode = InflateCodesMode.LENEXT;
- break;
- }
- if ((e & 64) == 0)
- {
- // next table
- need = e;
- tree_index = tindex / 3 + tree[tindex + 2];
- break;
- }
- if ((e & 32) != 0)
- {
- // End of block
- mode = InflateCodesMode.WASH;
- break;
- }
- mode = InflateCodesMode.BADCODE; // invalid code
- z.msg = "invalid literal/length code";
- r = (int)ZLibResultCode.Z_DATA_ERROR;
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
-
-
- case InflateCodesMode.LENEXT: // i: getting length extra (have base)
- j = get_Renamed;
-
- while (k < (j))
- {
- if (n != 0)
- r = (int)ZLibResultCode.Z_OK;
- else
- {
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- n--; b |= (z.next_in[p++] & 0xff) << k;
- k += 8;
- }
-
- count += (b & ZLibUtil.inflate_mask[j]);
-
- b >>= j;
- k -= j;
-
- need = dbits;
- tree = dtree;
- tree_index = dtree_index;
- mode = InflateCodesMode.DIST;
- goto case InflateCodesMode.DIST;
-
- case InflateCodesMode.DIST: // i: get distance next
- j = need;
-
- while (k < (j))
- {
- if (n != 0)
- r = (int)ZLibResultCode.Z_OK;
- else
- {
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- n--; b |= (z.next_in[p++] & 0xff) << k;
- k += 8;
- }
-
- tindex = (tree_index + (b & ZLibUtil.inflate_mask[j])) * 3;
-
- b >>= tree[tindex + 1];
- k -= tree[tindex + 1];
-
- e = (tree[tindex]);
- if ((e & 16) != 0)
- {
- // distance
- get_Renamed = e & 15;
- dist = tree[tindex + 2];
- mode = InflateCodesMode.DISTEXT;
- break;
- }
- if ((e & 64) == 0)
- {
- // next table
- need = e;
- tree_index = tindex / 3 + tree[tindex + 2];
- break;
- }
- mode = InflateCodesMode.BADCODE; // invalid code
- z.msg = "invalid distance code";
- r = (int)ZLibResultCode.Z_DATA_ERROR;
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
-
-
- case InflateCodesMode.DISTEXT: // i: getting distance extra
- j = get_Renamed;
-
- while (k < (j))
- {
- if (n != 0)
- r = (int)ZLibResultCode.Z_OK;
- else
- {
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- n--; b |= (z.next_in[p++] & 0xff) << k;
- k += 8;
- }
-
- dist += (b & ZLibUtil.inflate_mask[j]);
-
- b >>= j;
- k -= j;
-
- mode = InflateCodesMode.COPY;
- goto case InflateCodesMode.COPY;
-
- case InflateCodesMode.COPY: // o: copying bytes in Window, waiting for space
- f = q - dist;
- while (f < 0)
- {
- // modulo Window size-"while" instead
- f += s.End; // of "if" handles invalid distances
- }
- while (count != 0)
- {
-
- if (m == 0)
- {
- if (q == s.End && s.ReadPos != 0)
- {
- q = 0; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
- }
- if (m == 0)
- {
- s.WritePos = q; r = s.inflate_flush(z, r);
- q = s.WritePos; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
-
- if (q == s.End && s.ReadPos != 0)
- {
- q = 0; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
- }
-
- if (m == 0)
- {
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- }
- }
-
- s.Window[q++] = s.Window[f++]; m--;
-
- if (f == s.End)
- f = 0;
- count--;
- }
- mode = InflateCodesMode.START;
- break;
-
- case InflateCodesMode.LIT: // o: got literal, waiting for output space
- if (m == 0)
- {
- if (q == s.End && s.ReadPos != 0)
- {
- q = 0; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
- }
- if (m == 0)
- {
- s.WritePos = q; r = s.inflate_flush(z, r);
- q = s.WritePos; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
-
- if (q == s.End && s.ReadPos != 0)
- {
- q = 0; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
- }
- if (m == 0)
- {
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- }
- }
- r = (int)ZLibResultCode.Z_OK;
-
- s.Window[q++] = (byte) lit; m--;
-
- mode = InflateCodesMode.START;
- break;
-
- case InflateCodesMode.WASH: // o: got eob, possibly more output
- if (k > 7)
- {
- // return unused byte, if any
- k -= 8;
- n++;
- p--; // can always return one
- }
-
- s.WritePos = q; r = s.inflate_flush(z, r);
- q = s.WritePos; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
-
- if (s.ReadPos != s.WritePos)
- {
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
- }
- mode = InflateCodesMode.END;
- goto case InflateCodesMode.END;
-
- case InflateCodesMode.END:
- r = (int)ZLibResultCode.Z_STREAM_END;
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
-
-
- case InflateCodesMode.BADCODE: // x: got error
-
- r = (int)ZLibResultCode.Z_DATA_ERROR;
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
-
-
- default:
- r = (int)ZLibResultCode.Z_STREAM_ERROR;
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
- return s.inflate_flush(z, r);
-
- }
- }
- }
-
+ internal int proc(InfBlocks s, ZStream z, int r) {
+ int j; // temporary storage
+ //int[] t; // temporary pointer
+ int tindex; // temporary pointer
+ int e; // extra bits or operation
+ int b = 0; // bit buffer
+ int k = 0; // bits in bit buffer
+ int p = 0; // input data pointer
+ int n; // bytes available there
+ int q; // output Window WritePos pointer
+ int m; // bytes to End of Window or ReadPos pointer
+ int f; // pointer to copy strings from
+
+ // copy input/output information to locals (UPDATE macro restores)
+ p = z.next_in_index; n = z.avail_in; b = s.BitB; k = s.BitK;
+ q = s.WritePos; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+
+ // process input and output based on current state
+ while (true) {
+ switch (mode) {
+
+ // waiting for "i:"=input, "o:"=output, "x:"=nothing
+ case InflateCodesMode.START: // x: set up for InflateCodesMode.LEN
+ if (m >= 258 && n >= 10) {
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ r = inflate_fast(lbits, dbits, ltree, ltree_index, dtree, dtree_index, s, z);
+
+ p = z.next_in_index; n = z.avail_in; b = s.BitB; k = s.BitK;
+ q = s.WritePos; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+
+ if (r != (int)ZLibResultCode.Z_OK) {
+ mode = r == (int)ZLibResultCode.Z_STREAM_END ? InflateCodesMode.WASH : InflateCodesMode.BADCODE;
+ break;
+ }
+ }
+ need = lbits;
+ tree = ltree;
+ tree_index = ltree_index;
+
+ mode = InflateCodesMode.LEN;
+ goto case InflateCodesMode.LEN;
+
+ case InflateCodesMode.LEN: // i: get length/literal/eob next
+ j = need;
+
+ while (k < (j)) {
+ if (n != 0)
+ r = (int)ZLibResultCode.Z_OK;
+ else {
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ n--;
+ b |= (z.next_in[p++] & 0xff) << k;
+ k += 8;
+ }
+
+ tindex = (tree_index + (b & ZLibUtil.inflate_mask[j])) * 3;
+
+ b = ZLibUtil.URShift(b, (tree[tindex + 1]));
+ k -= (tree[tindex + 1]);
+
+ e = tree[tindex];
+
+ if (e == 0) {
+ // literal
+ lit = tree[tindex + 2];
+ mode = InflateCodesMode.LIT;
+ break;
+ }
+ if ((e & 16) != 0) {
+ // length
+ get_Renamed = e & 15;
+ count = tree[tindex + 2];
+ mode = InflateCodesMode.LENEXT;
+ break;
+ }
+ if ((e & 64) == 0) {
+ // next table
+ need = e;
+ tree_index = tindex / 3 + tree[tindex + 2];
+ break;
+ }
+ if ((e & 32) != 0) {
+ // End of block
+ mode = InflateCodesMode.WASH;
+ break;
+ }
+ mode = InflateCodesMode.BADCODE; // invalid code
+ z.msg = "invalid literal/length code";
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+
+
+ case InflateCodesMode.LENEXT: // i: getting length extra (have base)
+ j = get_Renamed;
+
+ while (k < (j)) {
+ if (n != 0)
+ r = (int)ZLibResultCode.Z_OK;
+ else {
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ n--; b |= (z.next_in[p++] & 0xff) << k;
+ k += 8;
+ }
+
+ count += (b & ZLibUtil.inflate_mask[j]);
+
+ b >>= j;
+ k -= j;
+
+ need = dbits;
+ tree = dtree;
+ tree_index = dtree_index;
+ mode = InflateCodesMode.DIST;
+ goto case InflateCodesMode.DIST;
+
+ case InflateCodesMode.DIST: // i: get distance next
+ j = need;
+
+ while (k < (j)) {
+ if (n != 0)
+ r = (int)ZLibResultCode.Z_OK;
+ else {
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ n--; b |= (z.next_in[p++] & 0xff) << k;
+ k += 8;
+ }
+
+ tindex = (tree_index + (b & ZLibUtil.inflate_mask[j])) * 3;
+
+ b >>= tree[tindex + 1];
+ k -= tree[tindex + 1];
+
+ e = (tree[tindex]);
+ if ((e & 16) != 0) {
+ // distance
+ get_Renamed = e & 15;
+ dist = tree[tindex + 2];
+ mode = InflateCodesMode.DISTEXT;
+ break;
+ }
+ if ((e & 64) == 0) {
+ // next table
+ need = e;
+ tree_index = tindex / 3 + tree[tindex + 2];
+ break;
+ }
+ mode = InflateCodesMode.BADCODE; // invalid code
+ z.msg = "invalid distance code";
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+
+
+ case InflateCodesMode.DISTEXT: // i: getting distance extra
+ j = get_Renamed;
+
+ while (k < (j)) {
+ if (n != 0)
+ r = (int)ZLibResultCode.Z_OK;
+ else {
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ n--; b |= (z.next_in[p++] & 0xff) << k;
+ k += 8;
+ }
+
+ dist += (b & ZLibUtil.inflate_mask[j]);
+
+ b >>= j;
+ k -= j;
+
+ mode = InflateCodesMode.COPY;
+ goto case InflateCodesMode.COPY;
+
+ case InflateCodesMode.COPY: // o: copying bytes in Window, waiting for space
+ f = q - dist;
+ while (f < 0) {
+ // modulo Window size-"while" instead
+ f += s.End; // of "if" handles invalid distances
+ }
+ while (count != 0) {
+
+ if (m == 0) {
+ if (q == s.End && s.ReadPos != 0) {
+ q = 0; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+ }
+ if (m == 0) {
+ s.WritePos = q; r = s.inflate_flush(z, r);
+ q = s.WritePos; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+
+ if (q == s.End && s.ReadPos != 0) {
+ q = 0; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+ }
+
+ if (m == 0) {
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ }
+ }
+
+ s.Window[q++] = s.Window[f++]; m--;
+
+ if (f == s.End)
+ f = 0;
+ count--;
+ }
+ mode = InflateCodesMode.START;
+ break;
+
+ case InflateCodesMode.LIT: // o: got literal, waiting for output space
+ if (m == 0) {
+ if (q == s.End && s.ReadPos != 0) {
+ q = 0; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+ }
+ if (m == 0) {
+ s.WritePos = q; r = s.inflate_flush(z, r);
+ q = s.WritePos; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+
+ if (q == s.End && s.ReadPos != 0) {
+ q = 0; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+ }
+ if (m == 0) {
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ }
+ }
+ r = (int)ZLibResultCode.Z_OK;
+
+ s.Window[q++] = (byte)lit; m--;
+
+ mode = InflateCodesMode.START;
+ break;
+
+ case InflateCodesMode.WASH: // o: got eob, possibly more output
+ if (k > 7) {
+ // return unused byte, if any
+ k -= 8;
+ n++;
+ p--; // can always return one
+ }
+
+ s.WritePos = q; r = s.inflate_flush(z, r);
+ q = s.WritePos; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+
+ if (s.ReadPos != s.WritePos) {
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+ }
+ mode = InflateCodesMode.END;
+ goto case InflateCodesMode.END;
+
+ case InflateCodesMode.END:
+ r = (int)ZLibResultCode.Z_STREAM_END;
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+
+
+ case InflateCodesMode.BADCODE: // x: got error
+
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+
+
+ default:
+ r = (int)ZLibResultCode.Z_STREAM_ERROR;
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+ return s.inflate_flush(z, r);
+
+ }
+ }
+ }
+
///
/// Frees allocated resources
///
- internal void free(ZStream z)
- {
- }
-
+ internal void free(ZStream z) {
+ }
- ///
+
+ ///
/// Fast inflate procedure. Called with number of bytes left to WritePos in Window at least 258
/// (the maximum string length) and number of input bytes available
/// at least ten. The ten bytes are six bytes for the longest length/
/// distance pair plus four bytes for overloading the bit buffer.
- ///
- internal int inflate_fast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InfBlocks s, ZStream z)
- {
- int t; // temporary pointer
- int[] tp; // temporary pointer
- int tp_index; // temporary pointer
- int e; // extra bits or operation
- int b; // bit buffer
- int k; // bits in bit buffer
- int p; // input data pointer
- int n; // bytes available there
- int q; // output Window WritePos pointer
- int m; // bytes to End of Window or ReadPos pointer
- int ml; // mask for literal/length tree
- int md; // mask for distance tree
- int c; // bytes to copy
- int d; // distance back to copy from
- int r; // copy source pointer
-
- // load input, output, bit values
- p = z.next_in_index; n = z.avail_in; b = s.BitB; k = s.BitK;
- q = s.WritePos; m = q < s.ReadPos?s.ReadPos - q - 1:s.End - q;
-
- // initialize masks
- ml = ZLibUtil.inflate_mask[bl];
- md = ZLibUtil.inflate_mask[bd];
-
- // do until not enough input or output space for fast loop
- do
- {
- // assume called with m >= 258 && n >= 10
- // get literal/length code
- while (k < (20))
- {
- // max bits for literal/length code
- n--;
- b |= (z.next_in[p++] & 0xff) << k; k += 8;
- }
-
- t = b & ml;
- tp = tl;
- tp_index = tl_index;
- if ((e = tp[(tp_index + t) * 3]) == 0)
- {
- b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
-
- s.Window[q++] = (byte) tp[(tp_index + t) * 3 + 2];
- m--;
- continue;
- }
- do
- {
-
- b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
-
- if ((e & 16) != 0)
- {
- e &= 15;
- c = tp[(tp_index + t) * 3 + 2] + ((int) b & ZLibUtil.inflate_mask[e]);
-
- b >>= e; k -= e;
-
- // decode distance base of block to copy
- while (k < (15))
- {
- // max bits for distance code
- n--;
- b |= (z.next_in[p++] & 0xff) << k; k += 8;
- }
-
- t = b & md;
- tp = td;
- tp_index = td_index;
- e = tp[(tp_index + t) * 3];
-
- do
- {
-
- b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
-
- if ((e & 16) != 0)
- {
- // get extra bits to add to distance base
- e &= 15;
- while (k < (e))
- {
- // get extra bits (up to 13)
- n--;
- b |= (z.next_in[p++] & 0xff) << k; k += 8;
- }
-
- d = tp[(tp_index + t) * 3 + 2] + (b & ZLibUtil.inflate_mask[e]);
-
- b >>= (e); k -= (e);
-
- // do the copy
- m -= c;
- if (q >= d)
- {
- // offset before dest
- // just copy
- r = q - d;
- if (q - r > 0 && 2 > (q - r))
- {
- s.Window[q++] = s.Window[r++]; c--; // minimum count is three,
- s.Window[q++] = s.Window[r++]; c--; // so unroll loop a little
- }
- else
- {
- Array.Copy(s.Window, r, s.Window, q, 2);
- q += 2; r += 2; c -= 2;
- }
- }
- else
- {
- // else offset after destination
- r = q - d;
- do
- {
- r += s.End; // force pointer in Window
- }
- while (r < 0); // covers invalid distances
- e = s.End - r;
- if (c > e)
- {
- // if source crosses,
- c -= e; // wrapped copy
- if (q - r > 0 && e > (q - r))
- {
- do
- {
- s.Window[q++] = s.Window[r++];
- }
- while (--e != 0);
- }
- else
- {
- Array.Copy(s.Window, r, s.Window, q, e);
- q += e; r += e; e = 0;
- }
- r = 0; // copy rest from start of Window
- }
- }
-
- // copy all or what's left
- if (q - r > 0 && c > (q - r))
- {
- do
- {
- s.Window[q++] = s.Window[r++];
- }
- while (--c != 0);
- }
- else
- {
- Array.Copy(s.Window, r, s.Window, q, c);
- q += c; r += c; c = 0;
- }
- break;
- }
- else if ((e & 64) == 0)
- {
- t += tp[(tp_index + t) * 3 + 2];
- t += (b & ZLibUtil.inflate_mask[e]);
- e = tp[(tp_index + t) * 3];
- }
- else
- {
- z.msg = "invalid distance code";
-
- c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3);
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
-
- return (int)ZLibResultCode.Z_DATA_ERROR;
- }
- }
- while (true);
- break;
- }
-
- if ((e & 64) == 0)
- {
- t += tp[(tp_index + t) * 3 + 2];
- t += (b & ZLibUtil.inflate_mask[e]);
- if ((e = tp[(tp_index + t) * 3]) == 0)
- {
-
- b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
-
- s.Window[q++] = (byte) tp[(tp_index + t) * 3 + 2];
- m--;
- break;
- }
- }
- else if ((e & 32) != 0)
- {
-
- c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3);
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
-
- return (int)ZLibResultCode.Z_STREAM_END;
- }
- else
- {
- z.msg = "invalid literal/length code";
-
- c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3);
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
-
- return (int)ZLibResultCode.Z_DATA_ERROR;
- }
- }
- while (true);
- }
- while (m >= 258 && n >= 10);
-
- // not enough input or output--restore pointers and return
- c = z.avail_in - n; c = (k >> 3) < c?k >> 3:c; n += c; p -= c; k -= (c << 3);
-
- s.BitB = b; s.BitK = k;
- z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
- s.WritePos = q;
-
- return (int)ZLibResultCode.Z_OK;
- }
+ ///
+ internal int inflate_fast(int bl, int bd, int[] tl, int tl_index, int[] td, int td_index, InfBlocks s, ZStream z) {
+ int t; // temporary pointer
+ int[] tp; // temporary pointer
+ int tp_index; // temporary pointer
+ int e; // extra bits or operation
+ int b; // bit buffer
+ int k; // bits in bit buffer
+ int p; // input data pointer
+ int n; // bytes available there
+ int q; // output Window WritePos pointer
+ int m; // bytes to End of Window or ReadPos pointer
+ int ml; // mask for literal/length tree
+ int md; // mask for distance tree
+ int c; // bytes to copy
+ int d; // distance back to copy from
+ int r; // copy source pointer
+
+ // load input, output, bit values
+ p = z.next_in_index; n = z.avail_in; b = s.BitB; k = s.BitK;
+ q = s.WritePos; m = q < s.ReadPos ? s.ReadPos - q - 1 : s.End - q;
+
+ // initialize masks
+ ml = ZLibUtil.inflate_mask[bl];
+ md = ZLibUtil.inflate_mask[bd];
+
+ // do until not enough input or output space for fast loop
+ do {
+ // assume called with m >= 258 && n >= 10
+ // get literal/length code
+ while (k < (20)) {
+ // max bits for literal/length code
+ n--;
+ b |= (z.next_in[p++] & 0xff) << k; k += 8;
+ }
+
+ t = b & ml;
+ tp = tl;
+ tp_index = tl_index;
+ if ((e = tp[(tp_index + t) * 3]) == 0) {
+ b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
+
+ s.Window[q++] = (byte)tp[(tp_index + t) * 3 + 2];
+ m--;
+ continue;
+ }
+ do {
+
+ b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
+
+ if ((e & 16) != 0) {
+ e &= 15;
+ c = tp[(tp_index + t) * 3 + 2] + ((int)b & ZLibUtil.inflate_mask[e]);
+
+ b >>= e; k -= e;
+
+ // decode distance base of block to copy
+ while (k < (15)) {
+ // max bits for distance code
+ n--;
+ b |= (z.next_in[p++] & 0xff) << k; k += 8;
+ }
+
+ t = b & md;
+ tp = td;
+ tp_index = td_index;
+ e = tp[(tp_index + t) * 3];
+
+ do {
+
+ b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
+
+ if ((e & 16) != 0) {
+ // get extra bits to add to distance base
+ e &= 15;
+ while (k < (e)) {
+ // get extra bits (up to 13)
+ n--;
+ b |= (z.next_in[p++] & 0xff) << k; k += 8;
+ }
+
+ d = tp[(tp_index + t) * 3 + 2] + (b & ZLibUtil.inflate_mask[e]);
+
+ b >>= (e); k -= (e);
+
+ // do the copy
+ m -= c;
+ if (q >= d) {
+ // offset before dest
+ // just copy
+ r = q - d;
+ if (q - r > 0 && 2 > (q - r)) {
+ s.Window[q++] = s.Window[r++]; c--; // minimum count is three,
+ s.Window[q++] = s.Window[r++]; c--; // so unroll loop a little
+ } else {
+ Array.Copy(s.Window, r, s.Window, q, 2);
+ q += 2; r += 2; c -= 2;
+ }
+ } else {
+ // else offset after destination
+ r = q - d;
+ do {
+ r += s.End; // force pointer in Window
+ }
+ while (r < 0); // covers invalid distances
+ e = s.End - r;
+ if (c > e) {
+ // if source crosses,
+ c -= e; // wrapped copy
+ if (q - r > 0 && e > (q - r)) {
+ do {
+ s.Window[q++] = s.Window[r++];
+ }
+ while (--e != 0);
+ } else {
+ Array.Copy(s.Window, r, s.Window, q, e);
+ q += e; r += e; e = 0;
+ }
+ r = 0; // copy rest from start of Window
+ }
+ }
+
+ // copy all or what's left
+ if (q - r > 0 && c > (q - r)) {
+ do {
+ s.Window[q++] = s.Window[r++];
+ }
+ while (--c != 0);
+ } else {
+ Array.Copy(s.Window, r, s.Window, q, c);
+ q += c; r += c; c = 0;
+ }
+ break;
+ } else if ((e & 64) == 0) {
+ t += tp[(tp_index + t) * 3 + 2];
+ t += (b & ZLibUtil.inflate_mask[e]);
+ e = tp[(tp_index + t) * 3];
+ } else {
+ z.msg = "invalid distance code";
+
+ c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3);
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ }
+ while (true);
+ break;
+ }
+
+ if ((e & 64) == 0) {
+ t += tp[(tp_index + t) * 3 + 2];
+ t += (b & ZLibUtil.inflate_mask[e]);
+ if ((e = tp[(tp_index + t) * 3]) == 0) {
+
+ b >>= (tp[(tp_index + t) * 3 + 1]); k -= (tp[(tp_index + t) * 3 + 1]);
+
+ s.Window[q++] = (byte)tp[(tp_index + t) * 3 + 2];
+ m--;
+ break;
+ }
+ } else if ((e & 32) != 0) {
+
+ c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3);
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+
+ return (int)ZLibResultCode.Z_STREAM_END;
+ } else {
+ z.msg = "invalid literal/length code";
+
+ c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3);
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ }
+ while (true);
+ }
+ while (m >= 258 && n >= 10);
+
+ // not enough input or output--restore pointers and return
+ c = z.avail_in - n; c = (k >> 3) < c ? k >> 3 : c; n += c; p -= c; k -= (c << 3);
+
+ s.BitB = b; s.BitK = k;
+ z.avail_in = n; z.total_in += p - z.next_in_index; z.next_in_index = p;
+ s.WritePos = q;
+
+ return (int)ZLibResultCode.Z_OK;
+ }
#endregion
}
diff --git a/Src/IronPython.Modules/zlib/zlib.net/InfTree.cs b/Src/IronPython.Modules/zlib/zlib.net/InfTree.cs
index 3a0be26d6..e3f5d4c45 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/InfTree.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/InfTree.cs
@@ -43,22 +43,20 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
-namespace ComponentAce.Compression.Libs.ZLib
-{
- ///
- /// Contains utility information for the InfTree class
- ///
- internal class InfTreeUtil
- {
+namespace ComponentAce.Compression.Libs.ZLib {
+ ///
+ /// Contains utility information for the InfTree class
+ ///
+ internal class InfTreeUtil {
internal const int MANY = 1440;
internal const int fixed_bl = 9;
internal const int fixed_bd = 5;
- internal static readonly int[] fixed_tl = new int[]{96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186,
- 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8,
- 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255};
+ internal static readonly int[] fixed_tl = new int[]{96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 192, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 160, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 224, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 144, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 208, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 176, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 240, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 200, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 168, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 232, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 152, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 216, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 184, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 248, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 196, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 164, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 228, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 148, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 212, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 180, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 244, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 204, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 172, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 236, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 156, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 220, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 188, 0, 8, 14, 0, 8, 142, 0, 8, 78, 0, 9, 252, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 194, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 162, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 226, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 146, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 210, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 178, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 242, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 202, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 170, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 234, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 154, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 218, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 186,
+ 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 250, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 198, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 166, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 230, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 150, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 214, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 182, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 246, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 206, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 174, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 238, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 158, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 222, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 190, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 254, 96, 7, 256, 0, 8, 80, 0, 8, 16, 84, 8, 115, 82, 7, 31, 0, 8, 112, 0, 8, 48, 0, 9, 193, 80, 7, 10, 0, 8, 96, 0, 8, 32, 0, 9, 161, 0, 8, 0, 0, 8, 128, 0, 8, 64, 0, 9, 225, 80, 7, 6, 0, 8, 88, 0, 8, 24, 0, 9, 145, 83, 7, 59, 0, 8, 120, 0, 8, 56, 0, 9, 209, 81, 7, 17, 0, 8, 104, 0, 8, 40, 0, 9, 177, 0, 8, 8, 0, 8, 136, 0, 8, 72, 0, 9, 241, 80, 7, 4, 0, 8, 84, 0, 8, 20, 85, 8, 227, 83, 7, 43, 0, 8, 116, 0, 8, 52, 0, 9, 201, 81, 7, 13, 0, 8, 100, 0, 8, 36, 0, 9, 169, 0, 8, 4, 0, 8, 132, 0, 8, 68, 0, 9, 233, 80, 7, 8, 0, 8, 92, 0, 8, 28, 0, 9, 153, 84, 7, 83, 0, 8, 124, 0, 8, 60, 0, 9, 217, 82, 7, 23, 0, 8, 108, 0, 8, 44, 0, 9, 185, 0, 8, 12, 0, 8, 140, 0, 8, 76, 0, 9, 249, 80, 7, 3, 0, 8, 82, 0, 8, 18, 85, 8, 163, 83, 7, 35, 0, 8, 114, 0, 8, 50, 0, 9, 197, 81, 7, 11, 0, 8, 98, 0, 8, 34, 0, 9, 165, 0, 8, 2, 0, 8, 130, 0, 8, 66, 0, 9, 229, 80, 7, 7, 0, 8, 90, 0, 8, 26, 0, 9, 149, 84, 7, 67, 0, 8, 122, 0, 8, 58, 0, 9, 213, 82, 7, 19, 0, 8, 106, 0, 8, 42, 0, 9, 181, 0, 8, 10, 0, 8, 138, 0, 8, 74, 0, 9, 245, 80, 7, 5, 0, 8, 86, 0, 8, 22, 192, 8, 0, 83, 7, 51, 0, 8, 118, 0, 8, 54, 0, 9, 205, 81, 7, 15, 0, 8, 102, 0, 8, 38, 0, 9, 173, 0, 8, 6, 0, 8, 134, 0, 8, 70, 0, 9, 237, 80, 7, 9, 0, 8, 94, 0, 8, 30, 0, 9, 157, 84, 7, 99, 0, 8, 126, 0, 8, 62, 0, 9, 221, 82, 7, 27, 0, 8, 110, 0, 8, 46, 0, 9, 189, 0, 8,
+ 14, 0, 8, 142, 0, 8, 78, 0, 9, 253, 96, 7, 256, 0, 8, 81, 0, 8, 17, 85, 8, 131, 82, 7, 31, 0, 8, 113, 0, 8, 49, 0, 9, 195, 80, 7, 10, 0, 8, 97, 0, 8, 33, 0, 9, 163, 0, 8, 1, 0, 8, 129, 0, 8, 65, 0, 9, 227, 80, 7, 6, 0, 8, 89, 0, 8, 25, 0, 9, 147, 83, 7, 59, 0, 8, 121, 0, 8, 57, 0, 9, 211, 81, 7, 17, 0, 8, 105, 0, 8, 41, 0, 9, 179, 0, 8, 9, 0, 8, 137, 0, 8, 73, 0, 9, 243, 80, 7, 4, 0, 8, 85, 0, 8, 21, 80, 8, 258, 83, 7, 43, 0, 8, 117, 0, 8, 53, 0, 9, 203, 81, 7, 13, 0, 8, 101, 0, 8, 37, 0, 9, 171, 0, 8, 5, 0, 8, 133, 0, 8, 69, 0, 9, 235, 80, 7, 8, 0, 8, 93, 0, 8, 29, 0, 9, 155, 84, 7, 83, 0, 8, 125, 0, 8, 61, 0, 9, 219, 82, 7, 23, 0, 8, 109, 0, 8, 45, 0, 9, 187, 0, 8, 13, 0, 8, 141, 0, 8, 77, 0, 9, 251, 80, 7, 3, 0, 8, 83, 0, 8, 19, 85, 8, 195, 83, 7, 35, 0, 8, 115, 0, 8, 51, 0, 9, 199, 81, 7, 11, 0, 8, 99, 0, 8, 35, 0, 9, 167, 0, 8, 3, 0, 8, 131, 0, 8, 67, 0, 9, 231, 80, 7, 7, 0, 8, 91, 0, 8, 27, 0, 9, 151, 84, 7, 67, 0, 8, 123, 0, 8, 59, 0, 9, 215, 82, 7, 19, 0, 8, 107, 0, 8, 43, 0, 9, 183, 0, 8, 11, 0, 8, 139, 0, 8, 75, 0, 9, 247, 80, 7, 5, 0, 8, 87, 0, 8, 23, 192, 8, 0, 83, 7, 51, 0, 8, 119, 0, 8, 55, 0, 9, 207, 81, 7, 15, 0, 8, 103, 0, 8, 39, 0, 9, 175, 0, 8, 7, 0, 8, 135, 0, 8, 71, 0, 9, 239, 80, 7, 9, 0, 8, 95, 0, 8, 31, 0, 9, 159, 84, 7, 99, 0, 8, 127, 0, 8, 63, 0, 9, 223, 82, 7, 27, 0, 8, 111, 0, 8, 47, 0, 9, 191, 0, 8, 15, 0, 8, 143, 0, 8, 79, 0, 9, 255};
internal static readonly int[] fixed_td = new int[] { 80, 5, 1, 87, 5, 257, 83, 5, 17, 91, 5, 4097, 81, 5, 5, 89, 5, 1025, 85, 5, 65, 93, 5, 16385, 80, 5, 3, 88, 5, 513, 84, 5, 33, 92, 5, 8193, 82, 5, 9, 90, 5, 2049, 86, 5, 129, 192, 5, 24577, 80, 5, 2, 87, 5, 385, 83, 5, 25, 91, 5, 6145, 81, 5, 7, 89, 5, 1537, 85, 5, 97, 93, 5, 24577, 80, 5, 4, 88, 5, 769, 84, 5, 49, 92, 5, 12289, 82, 5, 13, 90, 5, 3073, 86, 5, 193, 192, 5, 24577 };
@@ -75,9 +73,8 @@ internal class InfTreeUtil
internal const int BMAX = 15; // maximum bit length of any code
}
- internal sealed class InfTree
- {
-
+ internal sealed class InfTree {
+
#region Methods
///
@@ -86,300 +83,255 @@ internal sealed class InfTree
///
/// Return (int)ZLibResultCode.Z_OK on success, (int)ZLibResultCode.Z_DATA_ERROR if the given code set is incomplete (the tables are still built in this case), (int)ZLibResultCode.Z_DATA_ERROR if the input is invalid (an over-subscribed set of lengths), or (int)ZLibResultCode.Z_DATA_ERROR if not enough memory.
///
- private static int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v)
- {
-
- int a; // counter for codes of length k
- int[] c = new int[InfTreeUtil.BMAX + 1]; // bit length count table
- int f; // i repeats in table every internalFlush entries
- int g; // maximum code length
- int h; // table level
- int i; // counter, current code
- int j; // counter
- int k; // number of bits in current code
- int l; // bits per table (returned in m)
- int mask; // (1 << windowBits) - 1, to avoid cc -O bug on HP
- int p; // pointer into c[], buffer[], or v[]
- int q; // points to current table
- int[] r = new int[3]; // table entry for structure assignment
+ private static int huft_build(int[] b, int bindex, int n, int s, int[] d, int[] e, int[] t, int[] m, int[] hp, int[] hn, int[] v) {
+
+ int a; // counter for codes of length k
+ int[] c = new int[InfTreeUtil.BMAX + 1]; // bit length count table
+ int f; // i repeats in table every internalFlush entries
+ int g; // maximum code length
+ int h; // table level
+ int i; // counter, current code
+ int j; // counter
+ int k; // number of bits in current code
+ int l; // bits per table (returned in m)
+ int mask; // (1 << windowBits) - 1, to avoid cc -O bug on HP
+ int p; // pointer into c[], buffer[], or v[]
+ int q; // points to current table
+ int[] r = new int[3]; // table entry for structure assignment
int[] u = new int[InfTreeUtil.BMAX]; // table stack
- int w; // bits before this table == (l * h)
+ int w; // bits before this table == (l * h)
int[] x = new int[InfTreeUtil.BMAX + 1]; // bit offsets, then code stack
- int xp; // pointer into x
- int y; // number of dummy codes added
- int z; // number of entries in current table
-
- // Generate counts for each bit length
-
- p = 0; i = n;
- do
- {
- c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX
- }
- while (i != 0);
-
- if (c[0] == n)
- {
- // null input--all zero length codes
- t[0] = - 1;
- m[0] = 0;
- return (int)ZLibResultCode.Z_OK;
- }
-
- // Find minimum and maximum length, bound *m by those
- l = m[0];
+ int xp; // pointer into x
+ int y; // number of dummy codes added
+ int z; // number of entries in current table
+
+ // Generate counts for each bit length
+
+ p = 0; i = n;
+ do {
+ c[b[bindex + p]]++; p++; i--; // assume all entries <= BMAX
+ }
+ while (i != 0);
+
+ if (c[0] == n) {
+ // null input--all zero length codes
+ t[0] = -1;
+ m[0] = 0;
+ return (int)ZLibResultCode.Z_OK;
+ }
+
+ // Find minimum and maximum length, bound *m by those
+ l = m[0];
for (j = 1; j <= InfTreeUtil.BMAX; j++)
- if (c[j] != 0)
- break;
- k = j; // minimum code length
- if (l < j)
- {
- l = j;
- }
- for (i = InfTreeUtil.BMAX; i != 0; i--)
- {
- if (c[i] != 0)
- break;
- }
- g = i; // maximum code length
- if (l > i)
- {
- l = i;
- }
- m[0] = l;
-
- // Adjust last length count to fill out codes, if needed
- for (y = 1 << j; j < i; j++, y <<= 1)
- {
- if ((y -= c[j]) < 0)
- {
- return (int)ZLibResultCode.Z_DATA_ERROR;
- }
- }
- if ((y -= c[i]) < 0)
- {
- return (int)ZLibResultCode.Z_DATA_ERROR;
- }
- c[i] += y;
-
- // Generate starting offsets into the value table for each length
- x[1] = j = 0;
- p = 1; xp = 2;
- while (--i != 0)
- {
- // note that i == g from above
- x[xp] = (j += c[p]);
- xp++;
- p++;
- }
-
- // Make a table of values in order of bit lengths
- i = 0; p = 0;
- do
- {
- if ((j = b[bindex + p]) != 0)
- {
- v[x[j]++] = i;
- }
- p++;
- }
- while (++i < n);
- n = x[g]; // set n to length of v
-
- // Generate the Huffman codes and for each, make the table entries
- x[0] = i = 0; // first Huffman code is zero
- p = 0; // grab values in bit order
- h = - 1; // no tables yet--level -1
- w = - l; // bits decoded == (l * h)
- u[0] = 0; // just to keep compilers happy
- q = 0; // ditto
- z = 0; // ditto
-
- // go through the bit lengths (k already is bits in shortest code)
- for (; k <= g; k++)
- {
- a = c[k];
- while (a-- != 0)
- {
- // here i is the Huffman code of length k bits for value *p
- // make tables up to required level
- while (k > w + l)
- {
- h++;
- w += l; // previous table always l bits
- // compute minimum size table less than or equal to l bits
- z = g - w;
- z = (z > l)?l:z; // table size upper limit
- if ((f = 1 << (j = k - w)) > a + 1)
- {
- // try a k-windowBits bit table
- // too few codes for k-windowBits bit table
- f -= (a + 1); // deduct codes from patterns left
- xp = k;
- if (j < z)
- {
- while (++j < z)
- {
- // try smaller tables up to z bits
- if ((f <<= 1) <= c[++xp])
- break; // enough codes to use up j bits
- f -= c[xp]; // else deduct codes from patterns
- }
- }
- }
- z = 1 << j; // table entries for j-bit table
-
- // allocate new table
+ if (c[j] != 0)
+ break;
+ k = j; // minimum code length
+ if (l < j) {
+ l = j;
+ }
+ for (i = InfTreeUtil.BMAX; i != 0; i--) {
+ if (c[i] != 0)
+ break;
+ }
+ g = i; // maximum code length
+ if (l > i) {
+ l = i;
+ }
+ m[0] = l;
+
+ // Adjust last length count to fill out codes, if needed
+ for (y = 1 << j; j < i; j++, y <<= 1) {
+ if ((y -= c[j]) < 0) {
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ }
+ if ((y -= c[i]) < 0) {
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ c[i] += y;
+
+ // Generate starting offsets into the value table for each length
+ x[1] = j = 0;
+ p = 1; xp = 2;
+ while (--i != 0) {
+ // note that i == g from above
+ x[xp] = (j += c[p]);
+ xp++;
+ p++;
+ }
+
+ // Make a table of values in order of bit lengths
+ i = 0; p = 0;
+ do {
+ if ((j = b[bindex + p]) != 0) {
+ v[x[j]++] = i;
+ }
+ p++;
+ }
+ while (++i < n);
+ n = x[g]; // set n to length of v
+
+ // Generate the Huffman codes and for each, make the table entries
+ x[0] = i = 0; // first Huffman code is zero
+ p = 0; // grab values in bit order
+ h = -1; // no tables yet--level -1
+ w = -l; // bits decoded == (l * h)
+ u[0] = 0; // just to keep compilers happy
+ q = 0; // ditto
+ z = 0; // ditto
+
+ // go through the bit lengths (k already is bits in shortest code)
+ for (; k <= g; k++) {
+ a = c[k];
+ while (a-- != 0) {
+ // here i is the Huffman code of length k bits for value *p
+ // make tables up to required level
+ while (k > w + l) {
+ h++;
+ w += l; // previous table always l bits
+ // compute minimum size table less than or equal to l bits
+ z = g - w;
+ z = (z > l) ? l : z; // table size upper limit
+ if ((f = 1 << (j = k - w)) > a + 1) {
+ // try a k-windowBits bit table
+ // too few codes for k-windowBits bit table
+ f -= (a + 1); // deduct codes from patterns left
+ xp = k;
+ if (j < z) {
+ while (++j < z) {
+ // try smaller tables up to z bits
+ if ((f <<= 1) <= c[++xp])
+ break; // enough codes to use up j bits
+ f -= c[xp]; // else deduct codes from patterns
+ }
+ }
+ }
+ z = 1 << j; // table entries for j-bit table
+
+ // allocate new table
if (hn[0] + z > InfTreeUtil.MANY)
- // (note: doesn't matter for fixed)
- return (int)ZLibResultCode.Z_DATA_ERROR; // overflow of MANY
- u[h] = q = hn[0]; // DEBUG
- hn[0] += z;
-
- // connect to last table, if there is one
- if (h != 0)
- {
- x[h] = i; // save pattern for backing up
- r[0] = (byte) j; // bits in this table
- r[1] = (byte) l; // bits to dump before this table
- j = ZLibUtil.URShift(i, (w - l));
- r[2] = (int) (q - u[h - 1] - j); // offset to this table
- Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table
- }
- else
- {
- t[0] = q; // first table is returned result
- }
- }
-
- // set up table entry in r
- r[1] = (byte) (k - w);
- if (p >= n)
- {
- r[0] = 128 + 64; // out of values--invalid code
- }
- else if (v[p] < s)
- {
- r[0] = (byte) (v[p] < 256?0:32 + 64); // 256 is End-of-block
- r[2] = v[p++]; // simple code is just the value
- }
- else
- {
- r[0] = (byte) (e[v[p] - s] + 16 + 64); // non-simple--look up in lists
- r[2] = d[v[p++] - s];
- }
-
- // fill code-like entries with r
- f = 1 << (k - w);
- for (j = ZLibUtil.URShift(i, w); j < z; j += f)
- {
- Array.Copy(r, 0, hp, (q + j) * 3, 3);
- }
-
- // backwards increment the k-bit code i
- for (j = 1 << (k - 1); (i & j) != 0; j = ZLibUtil.URShift(j, 1))
- {
- i ^= j;
- }
- i ^= j;
-
- // backup over finished tables
- mask = (1 << w) - 1; // needed on HP, cc -O bug
- while ((i & mask) != x[h])
- {
- h--; // don't need to update q
- w -= l;
- mask = (1 << w) - 1;
- }
- }
- }
- // Return (int)ZLibResultCode.Z_DATA_ERROR if we were given an incomplete table
+ // (note: doesn't matter for fixed)
+ return (int)ZLibResultCode.Z_DATA_ERROR; // overflow of MANY
+ u[h] = q = hn[0]; // DEBUG
+ hn[0] += z;
+
+ // connect to last table, if there is one
+ if (h != 0) {
+ x[h] = i; // save pattern for backing up
+ r[0] = (byte)j; // bits in this table
+ r[1] = (byte)l; // bits to dump before this table
+ j = ZLibUtil.URShift(i, (w - l));
+ r[2] = (int)(q - u[h - 1] - j); // offset to this table
+ Array.Copy(r, 0, hp, (u[h - 1] + j) * 3, 3); // connect to last table
+ } else {
+ t[0] = q; // first table is returned result
+ }
+ }
+
+ // set up table entry in r
+ r[1] = (byte)(k - w);
+ if (p >= n) {
+ r[0] = 128 + 64; // out of values--invalid code
+ } else if (v[p] < s) {
+ r[0] = (byte)(v[p] < 256 ? 0 : 32 + 64); // 256 is End-of-block
+ r[2] = v[p++]; // simple code is just the value
+ } else {
+ r[0] = (byte)(e[v[p] - s] + 16 + 64); // non-simple--look up in lists
+ r[2] = d[v[p++] - s];
+ }
+
+ // fill code-like entries with r
+ f = 1 << (k - w);
+ for (j = ZLibUtil.URShift(i, w); j < z; j += f) {
+ Array.Copy(r, 0, hp, (q + j) * 3, 3);
+ }
+
+ // backwards increment the k-bit code i
+ for (j = 1 << (k - 1); (i & j) != 0; j = ZLibUtil.URShift(j, 1)) {
+ i ^= j;
+ }
+ i ^= j;
+
+ // backup over finished tables
+ mask = (1 << w) - 1; // needed on HP, cc -O bug
+ while ((i & mask) != x[h]) {
+ h--; // don't need to update q
+ w -= l;
+ mask = (1 << w) - 1;
+ }
+ }
+ }
+ // Return (int)ZLibResultCode.Z_DATA_ERROR if we were given an incomplete table
return y != 0 && g != 1 ? (int)ZLibResultCode.Z_BUF_ERROR : (int)ZLibResultCode.Z_OK;
- }
-
+ }
+
///
/// Build trees
///
- internal static int inflate_trees_bits(int[] c, int[] bb, int[] tb, int[] hp, ZStream z)
- {
- int r;
- int[] hn = new int[1]; // hufts used in space
- int[] v = new int[19]; // work area for huft_build
-
- r = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
-
- if (r == (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.msg = "oversubscribed dynamic bit lengths tree";
- }
- else if (r == (int)ZLibResultCode.Z_DATA_ERROR || bb[0] == 0)
- {
- z.msg = "incomplete dynamic bit lengths tree";
- r = (int)ZLibResultCode.Z_DATA_ERROR;
- }
- return r;
- }
-
+ internal static int inflate_trees_bits(int[] c, int[] bb, int[] tb, int[] hp, ZStream z) {
+ int r;
+ int[] hn = new int[1]; // hufts used in space
+ int[] v = new int[19]; // work area for huft_build
+
+ r = huft_build(c, 0, 19, 19, null, null, tb, bb, hp, hn, v);
+
+ if (r == (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.msg = "oversubscribed dynamic bit lengths tree";
+ } else if (r == (int)ZLibResultCode.Z_DATA_ERROR || bb[0] == 0) {
+ z.msg = "incomplete dynamic bit lengths tree";
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ return r;
+ }
+
///
/// Builds dynamic trees
///
- internal static int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, int[] tl, int[] td, int[] hp, ZStream z)
- {
- int r;
- int[] hn = new int[1]; // hufts used in space
- int[] v = new int[288]; // work area for huft_build
-
- // build literal/length tree
+ internal static int inflate_trees_dynamic(int nl, int nd, int[] c, int[] bl, int[] bd, int[] tl, int[] td, int[] hp, ZStream z) {
+ int r;
+ int[] hn = new int[1]; // hufts used in space
+ int[] v = new int[288]; // work area for huft_build
+
+ // build literal/length tree
r = huft_build(c, 0, nl, 257, InfTreeUtil.cplens, InfTreeUtil.cplext, tl, bl, hp, hn, v);
- if (r != (int)ZLibResultCode.Z_OK || bl[0] == 0)
- {
- if (r == (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.msg = "oversubscribed literal/length tree";
- }
- else if (r != (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.msg = "incomplete literal/length tree";
- r = (int)ZLibResultCode.Z_DATA_ERROR;
- }
- return r;
- }
-
- // build distance tree
+ if (r != (int)ZLibResultCode.Z_OK || bl[0] == 0) {
+ if (r == (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.msg = "oversubscribed literal/length tree";
+ } else if (r != (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.msg = "incomplete literal/length tree";
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ return r;
+ }
+
+ // build distance tree
r = huft_build(c, nl, nd, 0, InfTreeUtil.cpdist, InfTreeUtil.cpdext, td, bd, hp, hn, v);
-
- if (r != (int)ZLibResultCode.Z_OK || (bd[0] == 0 && nl > 257))
- {
- if (r == (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.msg = "oversubscribed distance tree";
- }
- else if (r == (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.msg = "incomplete distance tree";
- r = (int)ZLibResultCode.Z_DATA_ERROR;
- }
- else if (r != (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.msg = "empty distance tree with lengths";
- r = (int)ZLibResultCode.Z_DATA_ERROR;
- }
- return r;
- }
-
- return (int)ZLibResultCode.Z_OK;
- }
-
+
+ if (r != (int)ZLibResultCode.Z_OK || (bd[0] == 0 && nl > 257)) {
+ if (r == (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.msg = "oversubscribed distance tree";
+ } else if (r == (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.msg = "incomplete distance tree";
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+ } else if (r != (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.msg = "empty distance tree with lengths";
+ r = (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ return r;
+ }
+
+ return (int)ZLibResultCode.Z_OK;
+ }
+
///
/// Build fixed trees
///
- internal static int inflate_trees_fixed(int[] bl, int[] bd, int[][] tl, int[][] td, ZStream z)
- {
+ internal static int inflate_trees_fixed(int[] bl, int[] bd, int[][] tl, int[][] td, ZStream z) {
bl[0] = InfTreeUtil.fixed_bl;
bd[0] = InfTreeUtil.fixed_bd;
tl[0] = InfTreeUtil.fixed_tl;
td[0] = InfTreeUtil.fixed_td;
- return (int)ZLibResultCode.Z_OK;
+ return (int)ZLibResultCode.Z_OK;
}
#endregion
diff --git a/Src/IronPython.Modules/zlib/zlib.net/Inflate.cs b/Src/IronPython.Modules/zlib/zlib.net/Inflate.cs
index 6cf3e0d5b..f50f6375b 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/Inflate.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/Inflate.cs
@@ -44,17 +44,15 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
///
/// This enumeration contains modes of inflate processing
///
- internal enum InflateMode
- {
+ internal enum InflateMode {
///
/// waiting for method byte
///
- METHOD = 0,
+ METHOD = 0,
///
/// waiting for flag byte
///
@@ -110,15 +108,14 @@ internal enum InflateMode
}
- internal sealed class Inflate
- {
+ internal sealed class Inflate {
#region Fields
- ///
+ ///
/// current inflate mode
- ///
- public InflateMode mode;
+ ///
+ public InflateMode mode;
#region mode dependent information
@@ -126,8 +123,8 @@ internal sealed class Inflate
/// if FLAGS, method byte
///
private int method;
-
- // if CHECK, check values to compare
+
+ // if CHECK, check values to compare
///
/// computed check value
@@ -138,10 +135,10 @@ internal sealed class Inflate
/// stream check value
///
private long need;
-
- ///
+
+ ///
/// if BAD, inflateSync's marker bytes count
- ///
+ ///
private int marker;
#endregion
@@ -150,15 +147,15 @@ internal sealed class Inflate
///
/// flag for no wrapper
///
- private int nowrap;
+ private int nowrap;
///
/// log2(Window size) (8..15, defaults to 15)
///
private int wbits;
- private IEnumerator gzipHeaderRemover;
+ private IEnumerator gzipHeaderRemover;
- private bool detectHeader;
+ private bool detectHeader;
#endregion
@@ -166,7 +163,7 @@ internal sealed class Inflate
/// current inflate_blocks state
///
private InfBlocks blocks;
-
+
#endregion
#region Methods
@@ -176,30 +173,28 @@ internal sealed class Inflate
///
/// A ZStream object
/// A result code
- internal int inflateReset(ZStream z)
- {
+ internal int inflateReset(ZStream z) {
if (z?.istate == null)
return (int)ZLibResultCode.Z_STREAM_ERROR;
-
+
z.total_in = z.total_out = 0;
z.msg = null;
- z.istate.mode = z.istate.nowrap != 0? InflateMode.BLOCKS: InflateMode.METHOD;
+ z.istate.mode = z.istate.nowrap != 0 ? InflateMode.BLOCKS : InflateMode.METHOD;
z.istate.blocks.reset(z, null);
return (int)ZLibResultCode.Z_OK;
}
-
+
///
/// Finishes the inflate algorithm processing
///
/// A ZStream object
/// Operation result code
- internal int inflateEnd(ZStream z)
- {
- blocks?.free(z);
- blocks = null;
- // ZFREE(z, z->state);
- return (int)ZLibResultCode.Z_OK;
- }
+ internal int inflateEnd(ZStream z) {
+ blocks?.free(z);
+ blocks = null;
+ // ZFREE(z, z->state);
+ return (int)ZLibResultCode.Z_OK;
+ }
///
/// Initializes the inflate algorithm
@@ -207,46 +202,39 @@ internal int inflateEnd(ZStream z)
/// A ZStream object
/// Window size
/// Operation result code
- internal int inflateInit(ZStream z, int windowBits)
- {
- z.msg = null;
- blocks = null;
-
- // handle undocumented nowrap option (no zlib header or check)
- nowrap = 0;
+ internal int inflateInit(ZStream z, int windowBits) {
+ z.msg = null;
+ blocks = null;
+
+ // handle undocumented nowrap option (no zlib header or check)
+ nowrap = 0;
detectHeader = false;
- if (windowBits < 0)
- {
+ if (windowBits < 0) {
// deflate, no header
- windowBits = - windowBits;
- nowrap = 1;
- }
- else if ((windowBits & 16) != 0)
- {
+ windowBits = -windowBits;
+ nowrap = 1;
+ } else if ((windowBits & 16) != 0) {
gzipHeaderRemover = GzipHeader.CreateRemover(z);
windowBits &= ~16;
- }
- else if ((windowBits & 32) != 0)
- {
+ } else if ((windowBits & 32) != 0) {
detectHeader = true;
windowBits &= ~32;
}
- // set Window size
- if (windowBits < 8 || windowBits > 15)
- {
- inflateEnd(z);
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- }
- wbits = windowBits;
-
- z.istate.blocks = new InfBlocks(z, z.istate.nowrap == 0, 1 << windowBits);
-
- // reset state
- inflateReset(z);
- return (int)ZLibResultCode.Z_OK;
- }
+ // set Window size
+ if (windowBits < 8 || windowBits > 15) {
+ inflateEnd(z);
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ }
+ wbits = windowBits;
+
+ z.istate.blocks = new InfBlocks(z, z.istate.nowrap == 0, 1 << windowBits);
+
+ // reset state
+ inflateReset(z);
+ return (int)ZLibResultCode.Z_OK;
+ }
///
@@ -255,19 +243,17 @@ internal int inflateInit(ZStream z, int windowBits)
/// A ZStream object
/// Flush strategy
/// Operation result code
- internal int inflate(ZStream z, FlushStrategy flush)
- {
- int internalFlush = (int)flush;
+ internal int inflate(ZStream z, FlushStrategy flush) {
+ int internalFlush = (int)flush;
- if (z?.istate == null || z.next_in == null)
+ if (z?.istate == null || z.next_in == null)
return (int)ZLibResultCode.Z_STREAM_ERROR;
- int res_temp = internalFlush == (int)FlushStrategy.Z_FINISH
- ? (int)ZLibResultCode.Z_BUF_ERROR
- : (int)ZLibResultCode.Z_OK;
- int r = (int)ZLibResultCode.Z_BUF_ERROR;
+ int res_temp = internalFlush == (int)FlushStrategy.Z_FINISH
+ ? (int)ZLibResultCode.Z_BUF_ERROR
+ : (int)ZLibResultCode.Z_OK;
+ int r = (int)ZLibResultCode.Z_BUF_ERROR;
- if (detectHeader)
- {
+ if (detectHeader) {
if (z.avail_in == 0)
return r;
if (z.next_in[z.next_in_index] == 0x1F)
@@ -275,8 +261,7 @@ internal int inflate(ZStream z, FlushStrategy flush)
detectHeader = false;
}
- if (gzipHeaderRemover != null)
- {
+ if (gzipHeaderRemover != null) {
if (z.avail_in == 0)
return r;
if (gzipHeaderRemover.MoveNext())
@@ -287,300 +272,276 @@ internal int inflate(ZStream z, FlushStrategy flush)
nowrap = 1;
}
- while (true)
- {
+ while (true) {
- switch (z.istate.mode)
- {
-
- case InflateMode.METHOD:
-
- if (z.avail_in == 0)
+ switch (z.istate.mode) {
+
+ case InflateMode.METHOD:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != ZLibUtil.Z_DEFLATED)
- {
- z.istate.mode = InflateMode.BAD;
- z.msg = "unknown compression method";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
- if ((z.istate.method >> 4) + 8 > z.istate.wbits)
- {
- z.istate.mode = InflateMode.BAD;
- z.msg = "invalid Window size";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
- z.istate.mode = InflateMode.FLAG;
- goto case InflateMode.FLAG;
-
- case InflateMode.FLAG:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ if (((z.istate.method = z.next_in[z.next_in_index++]) & 0xf) != ZLibUtil.Z_DEFLATED) {
+ z.istate.mode = InflateMode.BAD;
+ z.msg = "unknown compression method";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+ if ((z.istate.method >> 4) + 8 > z.istate.wbits) {
+ z.istate.mode = InflateMode.BAD;
+ z.msg = "invalid Window size";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+ z.istate.mode = InflateMode.FLAG;
+ goto case InflateMode.FLAG;
+
+ case InflateMode.FLAG:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- int b = (z.next_in[z.next_in_index++]) & 0xff;
-
- if ((((z.istate.method << 8) + b) % 31) != 0)
- {
- z.istate.mode = InflateMode.BAD;
- z.msg = "incorrect header check";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
-
- if ((b & ZLibUtil.PRESET_DICT) == 0)
- {
- z.istate.mode = InflateMode.BLOCKS;
- break;
- }
- z.istate.mode = InflateMode.DICT4;
- goto case InflateMode.DICT4;
-
- case InflateMode.DICT4:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ int b = (z.next_in[z.next_in_index++]) & 0xff;
+
+ if ((((z.istate.method << 8) + b) % 31) != 0) {
+ z.istate.mode = InflateMode.BAD;
+ z.msg = "incorrect header check";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+
+ if ((b & ZLibUtil.PRESET_DICT) == 0) {
+ z.istate.mode = InflateMode.BLOCKS;
+ break;
+ }
+ z.istate.mode = InflateMode.DICT4;
+ goto case InflateMode.DICT4;
+
+ case InflateMode.DICT4:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need = ((long)(z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int) 0xff000000L);
- z.istate.mode = InflateMode.DICT3;
- goto case InflateMode.DICT3;
-
- case InflateMode.DICT3:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ z.istate.need = ((long)(z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int)0xff000000L);
+ z.istate.mode = InflateMode.DICT3;
+ goto case InflateMode.DICT3;
+
+ case InflateMode.DICT3:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (((long)(z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L);
- z.istate.mode = InflateMode.DICT2;
- goto case InflateMode.DICT2;
-
- case InflateMode.DICT2:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (((long)(z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L);
+ z.istate.mode = InflateMode.DICT2;
+ goto case InflateMode.DICT2;
+
+ case InflateMode.DICT2:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (((long)(z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L);
- z.istate.mode = InflateMode.DICT1;
- goto case InflateMode.DICT1;
-
- case InflateMode.DICT1:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (((long)(z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L);
+ z.istate.mode = InflateMode.DICT1;
+ goto case InflateMode.DICT1;
+
+ case InflateMode.DICT1:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
- z.adler = z.istate.need;
- z.istate.mode = InflateMode.DICT0;
- return (int)ZLibResultCode.Z_NEED_DICT;
-
- case InflateMode.DICT0:
- z.istate.mode = InflateMode.BAD;
- z.msg = "need dictionary";
- z.istate.marker = 0; // can try inflateSync
- return (int)ZLibResultCode.Z_STREAM_ERROR;
-
- case InflateMode.BLOCKS:
- r = z.istate.blocks.proc(z, r);
- if (r == (int)ZLibResultCode.Z_DATA_ERROR)
- {
- z.istate.mode = InflateMode.BAD;
- z.istate.marker = 0; // can try inflateSync
- break;
- }
- if (r == (int)ZLibResultCode.Z_OK)
- {
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
+ z.adler = z.istate.need;
+ z.istate.mode = InflateMode.DICT0;
+ return (int)ZLibResultCode.Z_NEED_DICT;
+
+ case InflateMode.DICT0:
+ z.istate.mode = InflateMode.BAD;
+ z.msg = "need dictionary";
+ z.istate.marker = 0; // can try inflateSync
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+
+ case InflateMode.BLOCKS:
+ r = z.istate.blocks.proc(z, r);
+ if (r == (int)ZLibResultCode.Z_DATA_ERROR) {
+ z.istate.mode = InflateMode.BAD;
+ z.istate.marker = 0; // can try inflateSync
+ break;
+ }
+ if (r == (int)ZLibResultCode.Z_OK) {
r = res_temp;
- }
- if (r != (int)ZLibResultCode.Z_STREAM_END)
- {
- return r;
- }
+ }
+ if (r != (int)ZLibResultCode.Z_STREAM_END) {
+ return r;
+ }
r = res_temp;
- z.istate.blocks.reset(z, z.istate.was);
- if (z.istate.nowrap != 0)
- {
- z.istate.mode = InflateMode.DONE;
- break;
- }
- z.istate.mode = InflateMode.CHECK4;
- goto case InflateMode.CHECK4;
-
- case InflateMode.CHECK4:
-
- if (z.avail_in == 0)
+ z.istate.blocks.reset(z, z.istate.was);
+ if (z.istate.nowrap != 0) {
+ z.istate.mode = InflateMode.DONE;
+ break;
+ }
+ z.istate.mode = InflateMode.CHECK4;
+ goto case InflateMode.CHECK4;
+
+ case InflateMode.CHECK4:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int) 0xff000000L);
- z.istate.mode = InflateMode.CHECK3;
- goto case InflateMode.CHECK3;
-
- case InflateMode.CHECK3:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ z.istate.need = ((z.next_in[z.next_in_index++] & 0xff) << 24) & unchecked((int)0xff000000L);
+ z.istate.mode = InflateMode.CHECK3;
+ goto case InflateMode.CHECK3;
+
+ case InflateMode.CHECK3:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L);
- z.istate.mode = InflateMode.CHECK2;
- goto case InflateMode.CHECK2;
-
- case InflateMode.CHECK2:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 16) & 0xff0000L);
+ z.istate.mode = InflateMode.CHECK2;
+ goto case InflateMode.CHECK2;
+
+ case InflateMode.CHECK2:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L);
- z.istate.mode = InflateMode.CHECK1;
- goto case InflateMode.CHECK1;
-
- case InflateMode.CHECK1:
-
- if (z.avail_in == 0)
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (((z.next_in[z.next_in_index++] & 0xff) << 8) & 0xff00L);
+ z.istate.mode = InflateMode.CHECK1;
+ goto case InflateMode.CHECK1;
+
+ case InflateMode.CHECK1:
+
+ if (z.avail_in == 0)
return r; r = res_temp;
-
- z.avail_in--; z.total_in++;
- z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
-
- if (unchecked(((int) (z.istate.was[0])) != ((int) (z.istate.need))))
- {
- z.istate.mode = InflateMode.BAD;
- z.msg = "incorrect data check";
- z.istate.marker = 5; // can't try inflateSync
- break;
- }
-
- z.istate.mode = InflateMode.DONE;
- goto case InflateMode.DONE;
-
- case InflateMode.DONE:
- return (int)ZLibResultCode.Z_STREAM_END;
-
- case InflateMode.BAD:
- return (int)ZLibResultCode.Z_DATA_ERROR;
-
- default:
- return (int)ZLibResultCode.Z_STREAM_ERROR;
-
- }
- }
- }
-
- ///
- /// Sets dictionary for the inflate operation
- ///
- /// A ZStream object
- /// An array of byte - dictionary
- /// Dictionary length
- /// Operation result code
- internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength)
- {
- int index = 0;
- int length = dictLength;
- if (z?.istate?.mode != InflateMode.DICT0)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
-
- if (Adler32.GetAdler32Checksum(1L, dictionary, 0, dictLength) != z.adler)
- {
- return (int)ZLibResultCode.Z_DATA_ERROR;
- }
-
- z.adler = Adler32.GetAdler32Checksum(0, null, 0, 0);
-
- if (length >= (1 << z.istate.wbits))
- {
- length = (1 << z.istate.wbits) - 1;
- index = dictLength - length;
- }
- z.istate.blocks.set_dictionary(dictionary, index, length);
- z.istate.mode = InflateMode.BLOCKS;
- return (int)ZLibResultCode.Z_OK;
- }
-
-
+
+ z.avail_in--; z.total_in++;
+ z.istate.need += (z.next_in[z.next_in_index++] & 0xffL);
+
+ if (unchecked(((int)(z.istate.was[0])) != ((int)(z.istate.need)))) {
+ z.istate.mode = InflateMode.BAD;
+ z.msg = "incorrect data check";
+ z.istate.marker = 5; // can't try inflateSync
+ break;
+ }
+
+ z.istate.mode = InflateMode.DONE;
+ goto case InflateMode.DONE;
+
+ case InflateMode.DONE:
+ return (int)ZLibResultCode.Z_STREAM_END;
+
+ case InflateMode.BAD:
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+
+ default:
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+
+ }
+ }
+ }
+
+ ///
+ /// Sets dictionary for the inflate operation
+ ///
+ /// A ZStream object
+ /// An array of byte - dictionary
+ /// Dictionary length
+ /// Operation result code
+ internal int inflateSetDictionary(ZStream z, byte[] dictionary, int dictLength) {
+ int index = 0;
+ int length = dictLength;
+ if (z?.istate?.mode != InflateMode.DICT0)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+
+ if (Adler32.GetAdler32Checksum(1L, dictionary, 0, dictLength) != z.adler) {
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+
+ z.adler = Adler32.GetAdler32Checksum(0, null, 0, 0);
+
+ if (length >= (1 << z.istate.wbits)) {
+ length = (1 << z.istate.wbits) - 1;
+ index = dictLength - length;
+ }
+ z.istate.blocks.set_dictionary(dictionary, index, length);
+ z.istate.mode = InflateMode.BLOCKS;
+ return (int)ZLibResultCode.Z_OK;
+ }
+
+
///
/// Inflate synchronization
///
/// A ZStream object
/// Operation result code
- internal int inflateSync(ZStream z)
- {
- int n; // number of bytes to look at
- int p; // pointer to bytes
- int m; // number of marker bytes found in a row
- long r, w; // temporaries to save _total_in and _total_out
-
- // set up
- if (z?.istate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- if (z.istate.mode != InflateMode.BAD)
- {
- z.istate.mode = InflateMode.BAD;
- z.istate.marker = 0;
- }
- if ((n = z.avail_in) == 0)
- return (int)ZLibResultCode.Z_BUF_ERROR;
- p = z.next_in_index;
- m = z.istate.marker;
-
- // search
- while (n != 0 && m < 4)
- {
- if (z.next_in[p] == ZLibUtil.mark[m])
- {
- m++;
- }
- else if (z.next_in[p] != 0)
- {
- m = 0;
- }
- else
- {
- m = 4 - m;
- }
- p++; n--;
- }
-
- // restore
- z.total_in += p - z.next_in_index;
- z.next_in_index = p;
- z.avail_in = n;
- z.istate.marker = m;
-
- // return no joy or set up to restart on a new block
- if (m != 4)
- {
- return (int)ZLibResultCode.Z_DATA_ERROR;
- }
- r = z.total_in; w = z.total_out;
- inflateReset(z);
- z.total_in = r; z.total_out = w;
- z.istate.mode = InflateMode.BLOCKS;
- return (int)ZLibResultCode.Z_OK;
- }
-
+ internal int inflateSync(ZStream z) {
+ int n; // number of bytes to look at
+ int p; // pointer to bytes
+ int m; // number of marker bytes found in a row
+ long r, w; // temporaries to save _total_in and _total_out
+
+ // set up
+ if (z?.istate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ if (z.istate.mode != InflateMode.BAD) {
+ z.istate.mode = InflateMode.BAD;
+ z.istate.marker = 0;
+ }
+ if ((n = z.avail_in) == 0)
+ return (int)ZLibResultCode.Z_BUF_ERROR;
+ p = z.next_in_index;
+ m = z.istate.marker;
+
+ // search
+ while (n != 0 && m < 4) {
+ if (z.next_in[p] == ZLibUtil.mark[m]) {
+ m++;
+ } else if (z.next_in[p] != 0) {
+ m = 0;
+ } else {
+ m = 4 - m;
+ }
+ p++; n--;
+ }
+
+ // restore
+ z.total_in += p - z.next_in_index;
+ z.next_in_index = p;
+ z.avail_in = n;
+ z.istate.marker = m;
+
+ // return no joy or set up to restart on a new block
+ if (m != 4) {
+ return (int)ZLibResultCode.Z_DATA_ERROR;
+ }
+ r = z.total_in; w = z.total_out;
+ inflateReset(z);
+ z.total_in = r; z.total_out = w;
+ z.istate.mode = InflateMode.BLOCKS;
+ return (int)ZLibResultCode.Z_OK;
+ }
+
///
- /// Returns true if inflate is currently at the End of a block generated
- /// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
- /// implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
- /// but removes the length bytes of the resulting empty stored block. When
- /// decompressing, PPP checks that at the End of input packet, inflate is
- /// waiting for these length bytes.
+ /// Returns true if inflate is currently at the End of a block generated
+ /// by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
+ /// implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
+ /// but removes the length bytes of the resulting empty stored block. When
+ /// decompressing, PPP checks that at the End of input packet, inflate is
+ /// waiting for these length bytes.
///
- internal int inflateSyncPoint(ZStream z)
- {
- if (z?.istate?.blocks == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- return z.istate.blocks.sync_point();
+ internal int inflateSyncPoint(ZStream z) {
+ if (z?.istate?.blocks == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ return z.istate.blocks.sync_point();
}
#endregion
diff --git a/Src/IronPython.Modules/zlib/zlib.net/StaticTree.cs b/Src/IronPython.Modules/zlib/zlib.net/StaticTree.cs
index cf7f7ec0b..4349421b7 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/StaticTree.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/StaticTree.cs
@@ -42,58 +42,54 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* and contributors of zlib.
*/
-namespace ComponentAce.Compression.Libs.ZLib
-{
-
- internal sealed class StaticTree
- {
+namespace ComponentAce.Compression.Libs.ZLib {
+
+ internal sealed class StaticTree {
#region Fields
-
- private const int BL_CODES = 19;
- private const int D_CODES = 30;
- private const int LITERALS = 256;
- private const int LENGTH_CODES = 29;
- private const int L_CODES = (LITERALS + 1 + LENGTH_CODES);
-
- ///
+
+ private const int BL_CODES = 19;
+ private const int D_CODES = 30;
+ private const int LITERALS = 256;
+ private const int LENGTH_CODES = 29;
+ private const int L_CODES = (LITERALS + 1 + LENGTH_CODES);
+
+ ///
/// Bit length codes must not exceed MAX_BL_BITS bits
- ///
- internal const int MAX_BL_BITS = 7;
-
- internal static readonly short[] static_ltree = new short[]{12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7
- , 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8};
+ ///
+ internal const int MAX_BL_BITS = 7;
+
+ internal static readonly short[] static_ltree = new short[]{12, 8, 140, 8, 76, 8, 204, 8, 44, 8, 172, 8, 108, 8, 236, 8, 28, 8, 156, 8, 92, 8, 220, 8, 60, 8, 188, 8, 124, 8, 252, 8, 2, 8, 130, 8, 66, 8, 194, 8, 34, 8, 162, 8, 98, 8, 226, 8, 18, 8, 146, 8, 82, 8, 210, 8, 50, 8, 178, 8, 114, 8, 242, 8, 10, 8, 138, 8, 74, 8, 202, 8, 42, 8, 170, 8, 106, 8, 234, 8, 26, 8, 154, 8, 90, 8, 218, 8, 58, 8, 186, 8, 122, 8, 250, 8, 6, 8, 134, 8, 70, 8, 198, 8, 38, 8, 166, 8, 102, 8, 230, 8, 22, 8, 150, 8, 86, 8, 214, 8, 54, 8, 182, 8, 118, 8, 246, 8, 14, 8, 142, 8, 78, 8, 206, 8, 46, 8, 174, 8, 110, 8, 238, 8, 30, 8, 158, 8, 94, 8, 222, 8, 62, 8, 190, 8, 126, 8, 254, 8, 1, 8, 129, 8, 65, 8, 193, 8, 33, 8, 161, 8, 97, 8, 225, 8, 17, 8, 145, 8, 81, 8, 209, 8, 49, 8, 177, 8, 113, 8, 241, 8, 9, 8, 137, 8, 73, 8, 201, 8, 41, 8, 169, 8, 105, 8, 233, 8, 25, 8, 153, 8, 89, 8, 217, 8, 57, 8, 185, 8, 121, 8, 249, 8, 5, 8, 133, 8, 69, 8, 197, 8, 37, 8, 165, 8, 101, 8, 229, 8, 21, 8, 149, 8, 85, 8, 213, 8, 53, 8, 181, 8, 117, 8, 245, 8, 13, 8, 141, 8, 77, 8, 205, 8, 45, 8, 173, 8, 109, 8, 237, 8, 29, 8, 157, 8, 93, 8, 221, 8, 61, 8, 189, 8, 125, 8, 253, 8, 19, 9, 275, 9, 147, 9, 403, 9, 83, 9, 339, 9, 211, 9, 467, 9, 51, 9, 307, 9, 179, 9, 435, 9, 115, 9, 371, 9, 243, 9, 499, 9, 11, 9, 267, 9, 139, 9, 395, 9, 75, 9, 331, 9, 203, 9, 459, 9, 43, 9, 299, 9, 171, 9, 427, 9, 107, 9, 363, 9, 235, 9, 491, 9, 27, 9, 283, 9, 155, 9, 411, 9, 91, 9, 347, 9, 219, 9, 475, 9, 59, 9, 315, 9, 187, 9, 443, 9, 123, 9, 379, 9, 251, 9, 507, 9, 7, 9, 263, 9, 135, 9, 391, 9, 71, 9, 327, 9, 199, 9, 455, 9, 39, 9, 295, 9, 167, 9, 423, 9, 103, 9, 359, 9, 231, 9, 487, 9, 23, 9, 279, 9, 151, 9, 407, 9, 87, 9, 343, 9, 215, 9, 471, 9, 55, 9, 311, 9, 183, 9, 439, 9, 119, 9, 375, 9, 247, 9, 503, 9, 15, 9, 271, 9, 143, 9, 399, 9, 79, 9, 335, 9, 207, 9, 463, 9, 47, 9, 303, 9, 175, 9, 431, 9, 111, 9, 367, 9, 239, 9, 495, 9, 31, 9, 287, 9, 159, 9, 415, 9, 95, 9, 351, 9, 223, 9, 479, 9, 63, 9, 319, 9, 191, 9, 447, 9, 127, 9, 383, 9, 255, 9, 511, 9, 0, 7, 64, 7
+ , 32, 7, 96, 7, 16, 7, 80, 7, 48, 7, 112, 7, 8, 7, 72, 7, 40, 7, 104, 7, 24, 7, 88, 7, 56, 7, 120, 7, 4, 7, 68, 7, 36, 7, 100, 7, 20, 7, 84, 7, 52, 7, 116, 7, 3, 8, 131, 8, 67, 8, 195, 8, 35, 8, 163, 8, 99, 8, 227, 8};
internal static readonly short[] static_dtree = new short[] { 0, 5, 16, 5, 8, 5, 24, 5, 4, 5, 20, 5, 12, 5, 28, 5, 2, 5, 18, 5, 10, 5, 26, 5, 6, 5, 22, 5, 14, 5, 30, 5, 1, 5, 17, 5, 9, 5, 25, 5, 5, 5, 21, 5, 13, 5, 29, 5, 3, 5, 19, 5, 11, 5, 27, 5, 7, 5, 23, 5 };
-
- internal static StaticTree static_l_desc;
-
- internal static StaticTree static_d_desc;
-
- internal static StaticTree static_bl_desc;
-
- internal short[] static_tree; // static tree or null
- internal int[] extra_bits; // extra bits for each code or null
- internal int extra_base; // base index for extra_bits
- internal int elems; // max number of elements in the tree
- internal int max_length; // max bit length for the codes
+
+ internal static StaticTree static_l_desc;
+
+ internal static StaticTree static_d_desc;
+
+ internal static StaticTree static_bl_desc;
+
+ internal short[] static_tree; // static tree or null
+ internal int[] extra_bits; // extra bits for each code or null
+ internal int extra_base; // base index for extra_bits
+ internal int elems; // max number of elements in the tree
+ internal int max_length; // max bit length for the codes
#endregion
#region Constructors
- internal StaticTree(short[] static_tree, int[] extra_bits, int extra_base, int elems, int max_length)
- {
- this.static_tree = static_tree;
- this.extra_bits = extra_bits;
- this.extra_base = extra_base;
- this.elems = elems;
- this.max_length = max_length;
- }
- static StaticTree()
- {
- static_l_desc = new StaticTree(static_ltree, ZLibUtil.extra_lbits, LITERALS + 1, L_CODES, ZLibUtil.MAX_WBITS);
+ internal StaticTree(short[] static_tree, int[] extra_bits, int extra_base, int elems, int max_length) {
+ this.static_tree = static_tree;
+ this.extra_bits = extra_bits;
+ this.extra_base = extra_base;
+ this.elems = elems;
+ this.max_length = max_length;
+ }
+ static StaticTree() {
+ static_l_desc = new StaticTree(static_ltree, ZLibUtil.extra_lbits, LITERALS + 1, L_CODES, ZLibUtil.MAX_WBITS);
static_d_desc = new StaticTree(static_dtree, ZLibUtil.extra_dbits, 0, D_CODES, ZLibUtil.MAX_WBITS);
static_bl_desc = new StaticTree(null, ZLibUtil.extra_blbits, 0, BL_CODES, MAX_BL_BITS);
}
diff --git a/Src/IronPython.Modules/zlib/zlib.net/Tree.cs b/Src/IronPython.Modules/zlib/zlib.net/Tree.cs
index 576be2f1b..8f5e26b30 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/Tree.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/Tree.cs
@@ -41,16 +41,12 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
-using System;
+namespace ComponentAce.Compression.Libs.ZLib {
-namespace ComponentAce.Compression.Libs.ZLib
-{
-
///
/// This class represents a tree and is used in the Deflate class
///
- internal sealed class Tree
- {
+ internal sealed class Tree {
#region Fields
@@ -76,8 +72,7 @@ internal sealed class Tree
///
/// The dynamic tree
///
- public short[] DynTree
- {
+ public short[] DynTree {
get { return dyn_tree; }
set { dyn_tree = value; }
}
@@ -85,16 +80,14 @@ public short[] DynTree
///
/// Largest code with non zero frequency
///
- public int MaxCode
- {
+ public int MaxCode {
get { return max_code; }
set { max_code = value; }
}
///
/// the corresponding static tree
///
- internal StaticTree StatDesc
- {
+ internal StaticTree StatDesc {
get { return stat_desc; }
set { stat_desc = value; }
}
@@ -108,101 +101,93 @@ internal StaticTree StatDesc
/// must not have side effects. _dist_code[256] and _dist_code[257] are never
/// used.
///
- internal static int d_code(int dist)
- {
+ internal static int d_code(int dist) {
return ((dist) < 256 ? ZLibUtil._dist_code[dist] : ZLibUtil._dist_code[256 + (ZLibUtil.URShift((dist), 7))]);
- }
-
- ///
- /// Compute the optimal bit lengths for a tree and update the total bit length
- /// for the current block.
- /// IN assertion: the fields freq and dad are set, heap[heap_max] and
- /// above are the tree nodes sorted by increasing frequency.
- /// OUT assertions: the field count is set to the optimal bit length, the
- /// array bl_count contains the frequencies for each bit length.
- /// The length opt_len is updated; static_len is also updated if stree is
- /// not null.
+ }
+
+ ///
+ /// Compute the optimal bit lengths for a tree and update the total bit length
+ /// for the current block.
+ /// IN assertion: the fields freq and dad are set, heap[heap_max] and
+ /// above are the tree nodes sorted by increasing frequency.
+ /// OUT assertions: the field count is set to the optimal bit length, the
+ /// array bl_count contains the frequencies for each bit length.
+ /// The length opt_len is updated; static_len is also updated if stree is
+ /// not null.
///
- private void gen_bitlen(Deflate s)
- {
- short[] tree = dyn_tree;
- short[] stree = stat_desc.static_tree;
- int[] extra = stat_desc.extra_bits;
- int base_Renamed = stat_desc.extra_base;
- int max_length = stat_desc.max_length;
- int h; // heap index
- int n, m; // iterate over the tree elements
- int bits; // bit length
- int xbits; // extra bits
- short f; // frequency
- int overflow = 0; // number of elements with bit length too large
+ private void gen_bitlen(Deflate s) {
+ short[] tree = dyn_tree;
+ short[] stree = stat_desc.static_tree;
+ int[] extra = stat_desc.extra_bits;
+ int base_Renamed = stat_desc.extra_base;
+ int max_length = stat_desc.max_length;
+ int h; // heap index
+ int n, m; // iterate over the tree elements
+ int bits; // bit length
+ int xbits; // extra bits
+ short f; // frequency
+ int overflow = 0; // number of elements with bit length too large
for (bits = 0; bits <= ZLibUtil.MAX_WBITS; bits++)
- s.bl_count[bits] = 0;
-
- // In a first pass, compute the optimal bit lengths (which may
- // overflow in the case of the bit length tree).
- tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
-
- for (h = s.heap_max + 1; h < ZLibUtil.HEAP_SIZE; h++)
- {
- n = s.heap[h];
- bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
- if (bits > max_length)
- {
- bits = max_length; overflow++;
- }
- tree[n * 2 + 1] = (short) bits;
- // We overwrite tree[n*2+1] which is no longer needed
-
- if (n > max_code)
- continue; // not a leaf node
-
- s.bl_count[bits]++;
- xbits = 0;
- if (n >= base_Renamed)
- xbits = extra[n - base_Renamed];
- f = tree[n * 2];
- s.opt_len += f * (bits + xbits);
- if (stree != null)
- s.static_len += f * (stree[n * 2 + 1] + xbits);
- }
- if (overflow == 0)
- return ;
-
- // This happens for example on obj2 and pic of the Calgary corpus
- // Find the first bit length which could increase:
- do
- {
- bits = max_length - 1;
- while (s.bl_count[bits] == 0)
- bits--;
- s.bl_count[bits]--; // move one leaf down the tree
- s.bl_count[bits + 1] = (short) (s.bl_count[bits + 1] + 2); // move one overflow item as its brother
- s.bl_count[max_length]--;
- // The brother of the overflow item also moves one step up,
- // but this does not affect bl_count[max_length]
- overflow -= 2;
- }
- while (overflow > 0);
-
- for (bits = max_length; bits != 0; bits--)
- {
- n = s.bl_count[bits];
- while (n != 0)
- {
- m = s.heap[--h];
- if (m > max_code)
- continue;
- if (tree[m * 2 + 1] != bits)
- {
- s.opt_len = (int) (s.opt_len + ((long) bits - (long) tree[m * 2 + 1]) * (long) tree[m * 2]);
- tree[m * 2 + 1] = (short) bits;
- }
- n--;
- }
- }
- }
+ s.bl_count[bits] = 0;
+
+ // In a first pass, compute the optimal bit lengths (which may
+ // overflow in the case of the bit length tree).
+ tree[s.heap[s.heap_max] * 2 + 1] = 0; // root of the heap
+
+ for (h = s.heap_max + 1; h < ZLibUtil.HEAP_SIZE; h++) {
+ n = s.heap[h];
+ bits = tree[tree[n * 2 + 1] * 2 + 1] + 1;
+ if (bits > max_length) {
+ bits = max_length; overflow++;
+ }
+ tree[n * 2 + 1] = (short)bits;
+ // We overwrite tree[n*2+1] which is no longer needed
+
+ if (n > max_code)
+ continue; // not a leaf node
+
+ s.bl_count[bits]++;
+ xbits = 0;
+ if (n >= base_Renamed)
+ xbits = extra[n - base_Renamed];
+ f = tree[n * 2];
+ s.opt_len += f * (bits + xbits);
+ if (stree != null)
+ s.static_len += f * (stree[n * 2 + 1] + xbits);
+ }
+ if (overflow == 0)
+ return;
+
+ // This happens for example on obj2 and pic of the Calgary corpus
+ // Find the first bit length which could increase:
+ do {
+ bits = max_length - 1;
+ while (s.bl_count[bits] == 0)
+ bits--;
+ s.bl_count[bits]--; // move one leaf down the tree
+ s.bl_count[bits + 1] = (short)(s.bl_count[bits + 1] + 2); // move one overflow item as its brother
+ s.bl_count[max_length]--;
+ // The brother of the overflow item also moves one step up,
+ // but this does not affect bl_count[max_length]
+ overflow -= 2;
+ }
+ while (overflow > 0);
+
+ for (bits = max_length; bits != 0; bits--) {
+ n = s.bl_count[bits];
+ while (n != 0) {
+ m = s.heap[--h];
+ if (m > max_code)
+ continue;
+ if (tree[m * 2 + 1] != bits) {
+ s.opt_len = (int)(s.opt_len + ((long)bits - (long)tree[m * 2 + 1]) * (long)tree[m * 2]);
+ tree[m * 2 + 1] = (short)bits;
+ }
+ n--;
+ }
+ }
+ }
///
/// Construct one Huffman tree and assigns the code bit strings and lengths.
@@ -212,92 +197,85 @@ private void gen_bitlen(Deflate s)
/// and corresponding code. The length opt_len is updated; static_len is
/// also updated if stree is not null. The field max_code is set.
///
- internal void build_tree(Deflate s)
- {
- short[] tree = dyn_tree;
- short[] stree = stat_desc.static_tree;
- int elems = stat_desc.elems;
- int n, m; // iterate over heap elements
- int max_code = - 1; // largest code with non zero frequency
- int node; // new node being created
-
- // Construct the initial heap, with least frequent element in
- // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
- // heap[0] is not used.
- s.heap_len = 0;
- s.heap_max = ZLibUtil.HEAP_SIZE;
-
- for (n = 0; n < elems; n++)
- {
- if (tree[n * 2] != 0)
- {
- s.heap[++s.heap_len] = max_code = n;
- s.depth[n] = 0;
- }
- else
- {
- tree[n * 2 + 1] = 0;
- }
- }
-
- // The pkzip format requires that at least one distance code exists,
- // and that at least one bit should be sent even if there is only one
- // possible code. So to avoid special checks later on we force at least
- // two codes of non zero frequency.
- while (s.heap_len < 2)
- {
- node = s.heap[++s.heap_len] = (max_code < 2?++max_code:0);
- tree[node * 2] = 1;
- s.depth[node] = 0;
- s.opt_len--;
- if (stree != null)
- s.static_len -= stree[node * 2 + 1];
- // node is 0 or 1 so it does not have extra bits
- }
- this.max_code = max_code;
-
- // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
- // establish sub-heaps of increasing lengths:
-
- for (n = s.heap_len / 2; n >= 1; n--)
- s.pqdownheap(tree, n);
-
- // Construct the Huffman tree by repeatedly combining the least two
- // frequent nodes.
-
- node = elems; // next internal node of the tree
- do
- {
- // n = node of least frequency
- n = s.heap[1];
- s.heap[1] = s.heap[s.heap_len--];
- s.pqdownheap(tree, 1);
- m = s.heap[1]; // m = node of next least frequency
-
- s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
- s.heap[--s.heap_max] = m;
-
- // Create a new node father of n and m
- tree[node * 2] = (short) (tree[n * 2] + tree[m * 2]);
- s.depth[node] = (byte) (System.Math.Max((byte) s.depth[n], (byte) s.depth[m]) + 1);
- tree[n * 2 + 1] = tree[m * 2 + 1] = (short) node;
-
- // and insert the new node in the heap
- s.heap[1] = node++;
- s.pqdownheap(tree, 1);
- }
- while (s.heap_len >= 2);
-
- s.heap[--s.heap_max] = s.heap[1];
-
- // At this point, the fields freq and dad are set. We can now
- // generate the bit lengths.
-
- gen_bitlen(s);
-
- // The field count is now set, we can generate the bit codes
- gen_codes(tree, max_code, s.bl_count);
- }
+ internal void build_tree(Deflate s) {
+ short[] tree = dyn_tree;
+ short[] stree = stat_desc.static_tree;
+ int elems = stat_desc.elems;
+ int n, m; // iterate over heap elements
+ int max_code = -1; // largest code with non zero frequency
+ int node; // new node being created
+
+ // Construct the initial heap, with least frequent element in
+ // heap[1]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+ // heap[0] is not used.
+ s.heap_len = 0;
+ s.heap_max = ZLibUtil.HEAP_SIZE;
+
+ for (n = 0; n < elems; n++) {
+ if (tree[n * 2] != 0) {
+ s.heap[++s.heap_len] = max_code = n;
+ s.depth[n] = 0;
+ } else {
+ tree[n * 2 + 1] = 0;
+ }
+ }
+
+ // The pkzip format requires that at least one distance code exists,
+ // and that at least one bit should be sent even if there is only one
+ // possible code. So to avoid special checks later on we force at least
+ // two codes of non zero frequency.
+ while (s.heap_len < 2) {
+ node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
+ tree[node * 2] = 1;
+ s.depth[node] = 0;
+ s.opt_len--;
+ if (stree != null)
+ s.static_len -= stree[node * 2 + 1];
+ // node is 0 or 1 so it does not have extra bits
+ }
+ this.max_code = max_code;
+
+ // The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
+ // establish sub-heaps of increasing lengths:
+
+ for (n = s.heap_len / 2; n >= 1; n--)
+ s.pqdownheap(tree, n);
+
+ // Construct the Huffman tree by repeatedly combining the least two
+ // frequent nodes.
+
+ node = elems; // next internal node of the tree
+ do {
+ // n = node of least frequency
+ n = s.heap[1];
+ s.heap[1] = s.heap[s.heap_len--];
+ s.pqdownheap(tree, 1);
+ m = s.heap[1]; // m = node of next least frequency
+
+ s.heap[--s.heap_max] = n; // keep the nodes sorted by frequency
+ s.heap[--s.heap_max] = m;
+
+ // Create a new node father of n and m
+ tree[node * 2] = (short)(tree[n * 2] + tree[m * 2]);
+ s.depth[node] = (byte)(System.Math.Max((byte)s.depth[n], (byte)s.depth[m]) + 1);
+ tree[n * 2 + 1] = tree[m * 2 + 1] = (short)node;
+
+ // and insert the new node in the heap
+ s.heap[1] = node++;
+ s.pqdownheap(tree, 1);
+ }
+ while (s.heap_len >= 2);
+
+ s.heap[--s.heap_max] = s.heap[1];
+
+ // At this point, the fields freq and dad are set. We can now
+ // generate the bit lengths.
+
+ gen_bitlen(s);
+
+ // The field count is now set, we can generate the bit codes
+ gen_codes(tree, max_code, s.bl_count);
+ }
///
/// Generate the codes for a given tree and bit counts (which need not be
@@ -307,48 +285,43 @@ internal void build_tree(Deflate s)
/// OUT assertion: the field code is set for all tree elements of non
/// zero code length.
///
- private static void gen_codes(short[] tree, int max_code, short[] bl_count)
- {
+ private static void gen_codes(short[] tree, int max_code, short[] bl_count) {
short[] next_code = new short[ZLibUtil.MAX_WBITS + 1]; // next code value for each bit length
- short code = 0; // running code value
- int bits; // bit index
- int n; // code index
-
- // The distribution counts are first used to generate the code values
- // without bit reversal.
- for (bits = 1; bits <= ZLibUtil.MAX_WBITS; bits++)
- {
- next_code[bits] = code = (short) ((code + bl_count[bits - 1]) << 1);
- }
-
- // Check that the bit counts in bl_count are consistent. The last code
- // must be all ones.
-
- for (n = 0; n <= max_code; n++)
- {
- int len = tree[n * 2 + 1];
- if (len == 0)
- continue;
- // Now reverse the bits
- tree[n * 2] = (short) (bi_reverse(next_code[len]++, len));
- }
- }
+ short code = 0; // running code value
+ int bits; // bit index
+ int n; // code index
+
+ // The distribution counts are first used to generate the code values
+ // without bit reversal.
+ for (bits = 1; bits <= ZLibUtil.MAX_WBITS; bits++) {
+ next_code[bits] = code = (short)((code + bl_count[bits - 1]) << 1);
+ }
+
+ // Check that the bit counts in bl_count are consistent. The last code
+ // must be all ones.
+
+ for (n = 0; n <= max_code; n++) {
+ int len = tree[n * 2 + 1];
+ if (len == 0)
+ continue;
+ // Now reverse the bits
+ tree[n * 2] = (short)(bi_reverse(next_code[len]++, len));
+ }
+ }
///
/// Reverse the first count bits of a code, using straightforward code (a faster
/// method would use a table)
///
- private static int bi_reverse(int code, int len)
- {
- int res = 0;
- do
- {
- res |= code & 1;
- code = ZLibUtil.URShift(code, 1);
- res <<= 1;
- }
- while (--len > 0);
- return ZLibUtil.URShift(res, 1);
+ private static int bi_reverse(int code, int len) {
+ int res = 0;
+ do {
+ res |= code & 1;
+ code = ZLibUtil.URShift(code, 1);
+ res <<= 1;
+ }
+ while (--len > 0);
+ return ZLibUtil.URShift(res, 1);
}
#endregion
diff --git a/Src/IronPython.Modules/zlib/zlib.net/ZStream.cs b/Src/IronPython.Modules/zlib/zlib.net/ZStream.cs
index cb3fde016..b264ac549 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/ZStream.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/ZStream.cs
@@ -45,22 +45,20 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#pragma warning disable 419 // msc: Ambiguous reference in cref attribute
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
///
/// ZStream is used to store user data to compress/decompress.
///
- public sealed class ZStream
- {
+ public sealed class ZStream {
#region Constants
-
+
private const int DEF_WBITS = ZLibUtil.MAX_WBITS;
#endregion
#region Fields
-
+
///
/// Next input byte array
///
@@ -75,7 +73,7 @@ public sealed class ZStream
/// Number of bytes available at _next_in
///
private int _avail_in;
-
+
///
/// total nb of input bytes ReadPos so far
///
@@ -133,8 +131,7 @@ public sealed class ZStream
///
/// Gets/Sets the next input byte array.
///
- public byte[] next_in
- {
+ public byte[] next_in {
get { return _next_in; }
set { _next_in = value; }
}
@@ -142,8 +139,7 @@ public byte[] next_in
///
/// Index of the first byte in the input array.
///
- public int next_in_index
- {
+ public int next_in_index {
get { return _next_in_index; }
set { _next_in_index = value; }
}
@@ -151,8 +147,7 @@ public int next_in_index
///
/// Gets/Sets the number of bytes available in the input buffer.
///
- public int avail_in
- {
+ public int avail_in {
get { return _avail_in; }
set { _avail_in = value; }
}
@@ -160,8 +155,7 @@ public int avail_in
///
/// Gets/Sets the total number of bytes in the input buffer.
///
- public long total_in
- {
+ public long total_in {
get { return _total_in; }
set { _total_in = value; }
}
@@ -169,8 +163,7 @@ public long total_in
///
/// Gets/Sets the buffer for the next output data.
///
- public byte[] next_out
- {
+ public byte[] next_out {
get { return _next_out; }
set { _next_out = value; }
}
@@ -178,8 +171,7 @@ public byte[] next_out
///
/// Gets/Sets the index of the first byte in the byte array to write to.
///
- public int next_out_index
- {
+ public int next_out_index {
get { return _next_out_index; }
set { _next_out_index = value; }
}
@@ -187,8 +179,7 @@ public int next_out_index
///
/// Gets/Sets the remaining free space in the buffer.
///
- public int avail_out
- {
+ public int avail_out {
get { return _avail_out; }
set { _avail_out = value; }
}
@@ -196,8 +187,7 @@ public int avail_out
///
/// Gets/Sets the total number of bytes in the output array.
///
- public long total_out
- {
+ public long total_out {
get { return _total_out; }
set { _total_out = value; }
}
@@ -205,8 +195,7 @@ public long total_out
///
/// Gets sets the last error message occurred during class operations.
///
- public string msg
- {
+ public string msg {
get { return _msg; }
set { _msg = value; }
}
@@ -214,8 +203,7 @@ public string msg
///
/// A deflate object to perform data compression
///
- internal Deflate dstate
- {
+ internal Deflate dstate {
get { return _dstate; }
set { _dstate = value; }
}
@@ -223,8 +211,7 @@ internal Deflate dstate
///
/// Inflate object to perform data decompression
///
- internal Inflate istate
- {
+ internal Inflate istate {
get { return _istate; }
set { _istate = value; }
}
@@ -251,10 +238,9 @@ public bool IsInitialized {
/// apart from reading the ZLib header if present: this will be done by . (So and
/// may be modified, but and are unchanged.)
///
- public int inflateInit()
- {
- return inflateInit(DEF_WBITS);
- }
+ public int inflateInit() {
+ return inflateInit(DEF_WBITS);
+ }
///
/// This is another version of with an extra parameter. The fields , must be
@@ -274,12 +260,11 @@ public int inflateInit()
/// if present: this will be done by . (So and may be modified,
/// but and are unchanged.)
///
- public int inflateInit(int windowBits)
- {
- _istate = new Inflate();
- return _istate.inflateInit(this, windowBits);
- }
-
+ public int inflateInit(int windowBits) {
+ _istate = new Inflate();
+ return _istate.inflateInit(this, windowBits);
+ }
+
///
/// This method decompresses as much data as possible, and stops when the input buffer () becomes empty or
/// the output buffer () becomes full. It may some introduce some output latency (reading input without producing any output)
@@ -332,12 +317,11 @@ public int inflateInit(int windowBits)
/// when is used. In the case, the application
/// may then call to look for a good compression block.
///
- public int inflate(FlushStrategy flush)
- {
- if (_istate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- return _istate.inflate(this, flush);
- }
+ public int inflate(FlushStrategy flush) {
+ if (_istate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ return _istate.inflate(this, flush);
+ }
///
/// All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any
@@ -347,17 +331,16 @@ public int inflate(FlushStrategy flush)
/// inflateEnd returns if success,
/// if the stream state was inconsistent. In the error case, msg may be set but then points to a static string (which must not be deallocated).
///
- public int inflateEnd()
- {
- next_in_index = 0;
- next_out_index = 0;
-
- if (_istate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- int ret = _istate.inflateEnd(this);
- _istate = null;
- return ret;
- }
+ public int inflateEnd() {
+ next_in_index = 0;
+ next_out_index = 0;
+
+ if (_istate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ int ret = _istate.inflateEnd(this);
+ _istate = null;
+ return ret;
+ }
///
/// Skips invalid compressed data until a full flush point (see the description of deflate with Z_FULL_FLUSH) can be found,
@@ -370,12 +353,11 @@ public int inflateEnd()
/// current value of which indicates where valid compressed data was found. In the error case, the application may repeatedly
/// call , providing more input each time, until success or end of the input data.
///
- public int inflateSync()
- {
- if (_istate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- return _istate.inflateSync(this);
- }
+ public int inflateSync() {
+ if (_istate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ return _istate.inflateSync(this);
+ }
///
/// Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called immediately after a call of if this call returned . The dictionary chosen by the compressor can be determined from the Adler32 value returned by this call of . The compressor and decompresser must use exactly the same dictionary.
@@ -385,12 +367,11 @@ public int inflateSync()
///
/// inflateSetDictionary returns if success, if a parameter is invalid (such as null dictionary) or the stream state is inconsistent, if the given dictionary doesn't match the expected one (incorrect Adler32 value). inflateSetDictionary does not perform any decompression: this will be done by subsequent calls of .
///
- public int inflateSetDictionary(byte[] dictionary, int dictLength)
- {
- if (_istate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- return _istate.inflateSetDictionary(this, dictionary, dictLength);
- }
+ public int inflateSetDictionary(byte[] dictionary, int dictLength) {
+ if (_istate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ return _istate.inflateSetDictionary(this, dictionary, dictLength);
+ }
///
/// Initializes the internal stream state for compression.
@@ -401,10 +382,9 @@ public int inflateSetDictionary(byte[] dictionary, int dictLength)
/// if level is not a valid compression level. is set to null if there is
/// no error message. does not perform any compression: this will be done by .
///
- public int DeflateInit(int level)
- {
- return DeflateInit(level, ZLibUtil.MAX_WBITS);
- }
+ public int DeflateInit(int level) {
+ return DeflateInit(level, ZLibUtil.MAX_WBITS);
+ }
///
/// Initializes the internal stream state for compression.
@@ -418,11 +398,10 @@ public int DeflateInit(int level)
/// if level is not a valid compression level. is set to null if there
/// is no error message. does not perform any compression: this will be done by .
///
- public int DeflateInit(int level, int bits)
- {
- _dstate = new Deflate();
- return _dstate.DeflateInit(this, level, bits);
- }
+ public int DeflateInit(int level, int bits) {
+ _dstate = new Deflate();
+ return _dstate.DeflateInit(this, level, bits);
+ }
public int DeflateInit(int level, int windowBits, int memLevel, CompressionStrategy strategy) {
_dstate = new Deflate();
@@ -431,7 +410,7 @@ public int DeflateInit(int level, int windowBits, int memLevel, CompressionStrat
public int reset() {
if (_dstate != null) {
- return _dstate.deflateReset(this);
+ return _dstate.deflateReset(this);
}
if (_istate != null) {
@@ -510,14 +489,12 @@ public int reset() {
/// (for example or was zero).
///
///
- public int deflate(FlushStrategy flush)
- {
- if (_dstate == null)
- {
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- }
- return _dstate.deflate(this, flush);
- }
+ public int deflate(FlushStrategy flush) {
+ if (_dstate == null) {
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ }
+ return _dstate.deflate(this, flush);
+ }
///
/// All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending
@@ -528,17 +505,16 @@ public int deflate(FlushStrategy flush)
/// if the stream was freed prematurely (some input or output was discarded). In the error case,
/// may be set but then points to a static string (which must not be deallocated).
///
- public int deflateEnd()
- {
- next_in_index = 0;
- next_out_index = 0;
-
- if (_dstate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- int ret = _dstate.deflateEnd();
- _dstate = null;
- return ret;
- }
+ public int deflateEnd() {
+ next_in_index = 0;
+ next_out_index = 0;
+
+ if (_dstate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ int ret = _dstate.deflateEnd();
+ _dstate = null;
+ return ret;
+ }
///
/// Dynamically update the compression level and compression strategy. The interpretation of level is as in .
@@ -556,12 +532,11 @@ public int deflateEnd()
/// deflateParams returns if success, if the source stream
/// state was inconsistent or if a parameter was invalid, if was zero.
///
- public int deflateParams(int level, CompressionStrategy strategy)
- {
- if (_dstate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- return _dstate.deflateParams(this, level, strategy);
- }
+ public int deflateParams(int level, CompressionStrategy strategy) {
+ if (_dstate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ return _dstate.deflateParams(this, level, strategy);
+ }
///
/// Initializes the compression dictionary from the given byte sequence without producing any compressed output. This function must be called
@@ -589,71 +564,65 @@ public int deflateParams(int level, CompressionStrategy strategy)
/// called for this stream or if the compression method is bsort). does not perform any compression:
/// this will be done by .
///
- public int deflateSetDictionary(byte[] dictionary, int dictLength)
- {
- if (_dstate == null)
- return (int)ZLibResultCode.Z_STREAM_ERROR;
- return _dstate.deflateSetDictionary(this, dictionary, dictLength);
- }
+ public int deflateSetDictionary(byte[] dictionary, int dictLength) {
+ if (_dstate == null)
+ return (int)ZLibResultCode.Z_STREAM_ERROR;
+ return _dstate.deflateSetDictionary(this, dictionary, dictLength);
+ }
///
/// Flush as much pending output as possible. All output goes through this function so some applications may wish to
/// modify it to avoid allocating a large buffer and copying into it.
///
///
- public void FlushPending()
- {
- int len = _dstate.Pending;
-
- if (len > _avail_out)
- len = _avail_out;
- if (len == 0)
- return ;
-
- Array.Copy(_dstate.Pending_buf, _dstate.Pending_out, _next_out, _next_out_index, len);
-
- _next_out_index += len;
- _dstate.Pending_out += len;
- _total_out += len;
- _avail_out -= len;
- _dstate.Pending -= len;
- if (_dstate.Pending == 0)
- {
- _dstate.Pending_out = 0;
- }
- }
+ public void FlushPending() {
+ int len = _dstate.Pending;
+
+ if (len > _avail_out)
+ len = _avail_out;
+ if (len == 0)
+ return;
+
+ Array.Copy(_dstate.Pending_buf, _dstate.Pending_out, _next_out, _next_out_index, len);
+
+ _next_out_index += len;
+ _dstate.Pending_out += len;
+ _total_out += len;
+ _avail_out -= len;
+ _dstate.Pending -= len;
+ if (_dstate.Pending == 0) {
+ _dstate.Pending_out = 0;
+ }
+ }
///
/// Read a new buffer from the current input stream, update the adler32 and total number of bytes read. All input goes
/// through this function so some applications may wish to modify it to avoid allocating a large buffer and copying from it.
///
///
- public int ReadBuf(byte[] buf, int start, int size)
- {
- int len = _avail_in;
-
- if (len > size)
- len = size;
- if (len == 0)
- return 0;
-
- _avail_in -= len;
-
- if (_dstate.NoHeader == 0)
- {
- adler = Adler32.GetAdler32Checksum(adler, _next_in, _next_in_index, len);
- }
- Array.Copy(_next_in, _next_in_index, buf, start, len);
- _next_in_index += len;
- _total_in += len;
- return len;
- }
+ public int ReadBuf(byte[] buf, int start, int size) {
+ int len = _avail_in;
+
+ if (len > size)
+ len = size;
+ if (len == 0)
+ return 0;
+
+ _avail_in -= len;
+
+ if (_dstate.NoHeader == 0) {
+ adler = Adler32.GetAdler32Checksum(adler, _next_in, _next_in_index, len);
+ }
+ Array.Copy(_next_in, _next_in_index, buf, start, len);
+ _next_in_index += len;
+ _total_in += len;
+ return len;
+ }
///
/// Frees all inner buffers.
///
- public void free()
- {
+ public void free() {
_next_in = null;
_next_out = null;
_msg = null;
diff --git a/Src/IronPython.Modules/zlib/zlib.net/ZStreamException.cs b/Src/IronPython.Modules/zlib/zlib.net/ZStreamException.cs
index e0204d4b0..9a128c5e9 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/ZStreamException.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/ZStreamException.cs
@@ -42,27 +42,23 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* and contributors of zlib.
*/
-namespace ComponentAce.Compression.Libs.ZLib
-{
- ///
- /// Exceptions that occur in ZStream
- ///
- public class ZStreamException : System.IO.IOException
- {
+namespace ComponentAce.Compression.Libs.ZLib {
+ ///
+ /// Exceptions that occur in ZStream
+ ///
+ public class ZStreamException : System.IO.IOException {
///
/// Default constructor.
///
public ZStreamException()
- :base()
- {
- }
-
+ : base() {
+ }
+
///
/// Constructor which takes one parameter - an error message
///
- public ZStreamException(System.String s)
- :base(s)
- {
- }
- }
+ public ZStreamException(System.String s)
+ : base(s) {
+ }
+ }
}
\ No newline at end of file
diff --git a/Src/IronPython.Modules/zlib/zlib.net/Zlib.cs b/Src/IronPython.Modules/zlib/zlib.net/Zlib.cs
index 129d5647c..ec1760997 100644
--- a/Src/IronPython.Modules/zlib/zlib.net/Zlib.cs
+++ b/Src/IronPython.Modules/zlib/zlib.net/Zlib.cs
@@ -44,13 +44,11 @@ EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Text;
-namespace ComponentAce.Compression.Libs.ZLib
-{
+namespace ComponentAce.Compression.Libs.ZLib {
///
/// Some constants for specifying compression levels. Methods which takes a compression level as a parameter expects an integer value from 0 to 9. You can either specify an integer value or use constants for some most widely used compression levels.
///
- public static class ZLibCompressionLevel
- {
+ public static class ZLibCompressionLevel {
///
/// No compression should be used at all.
///
@@ -72,8 +70,7 @@ public static class ZLibCompressionLevel
///
/// Compression strategies. The strategy parameter is used to tune the compression algorithm. The strategy parameter only affects the compression ratio but not the correctness of the compressed output even if it is not set appropriately.
///
- public enum CompressionStrategy
- {
+ public enum CompressionStrategy {
///
/// This strategy is designed for filtered data. Data which consists of mostly small values, with random distribution should use Z_FILTERED. With this strategy, less string matching is performed.
///
@@ -91,8 +88,7 @@ public enum CompressionStrategy
///
/// Flush strategies
///
- public enum FlushStrategy
- {
+ public enum FlushStrategy {
///
/// Do not internalFlush data, but just write data as normal to the output buffer. This is the normal way in which data is written to the output buffer.
///
@@ -118,8 +114,7 @@ public enum FlushStrategy
///
/// Results of operations in ZLib library
///
- public enum ZLibResultCode
- {
+ public enum ZLibResultCode {
///
/// No failure was encountered, the operation completed without problem.
///
@@ -135,34 +130,33 @@ public enum ZLibResultCode
///
/// An internal error occurred
///
- Z_ERRNO = - 1,
+ Z_ERRNO = -1,
///
/// The stream structure was inconsistent
///
- Z_STREAM_ERROR = - 2,
+ Z_STREAM_ERROR = -2,
///
/// Input data has been corrupted (for decompression).
///
- Z_DATA_ERROR = - 3,
+ Z_DATA_ERROR = -3,
///
/// Memory allocation failed.
///
- Z_MEM_ERROR = - 4,
+ Z_MEM_ERROR = -4,
///
/// There was not enough space in the output buffer.
///
- Z_BUF_ERROR = - 5,
+ Z_BUF_ERROR = -5,
///
/// The version supplied does not match that supported by the ZLib module.
///
- Z_VERSION_ERROR = - 6
+ Z_VERSION_ERROR = -6
}
///
/// States of deflate operation
///
- internal enum DeflateState
- {
+ internal enum DeflateState {
INIT_STATE = 42,
BUSY_STATE = 113,
FINISH_STATE = 666
@@ -171,8 +165,7 @@ internal enum DeflateState
///
/// Data block types, i.e. binary or ascii text
///
- public enum BlockType
- {
+ public enum BlockType {
Z_BINARY = 0,
Z_ASCII = 1,
Z_UNKNOWN = 2
@@ -181,12 +174,10 @@ public enum BlockType
///
/// Helper class
///
- public static class ZLibUtil
- {
+ public static class ZLibUtil {
#region Copy large array to a small one in several steps
- internal class CopyLargeArrayToSmall
- {
+ internal class CopyLargeArrayToSmall {
private static byte[] srcBuf;
private static int srcOff;
@@ -196,8 +187,7 @@ internal class CopyLargeArrayToSmall
private static int destLen;
private static int nWritten;
- public static void Initialize(byte[] srcBuf, int srcOff, int srcDataLen, byte[] destBuff, int destOff, int destLen)
- {
+ public static void Initialize(byte[] srcBuf, int srcOff, int srcDataLen, byte[] destBuff, int destOff, int destLen) {
ZLibUtil.CopyLargeArrayToSmall.srcBuf = srcBuf;
ZLibUtil.CopyLargeArrayToSmall.srcOff = srcOff;
ZLibUtil.CopyLargeArrayToSmall.srcDataLen = srcDataLen;
@@ -206,25 +196,21 @@ public static void Initialize(byte[] srcBuf, int srcOff, int srcDataLen, byte[]
ZLibUtil.CopyLargeArrayToSmall.destLen = destLen;
ZLibUtil.CopyLargeArrayToSmall.nWritten = 0;
}
-
+
public static int GetRemainingDataSize() { return srcDataLen; }
///
/// Copies large array which was passed as srcBuf to the Initialize method into the destination array which were passes as destBuff
///
/// The number of bytes copied
- public static int CopyData()
- {
- if (srcDataLen > destLen)
- {
+ public static int CopyData() {
+ if (srcDataLen > destLen) {
Array.Copy(srcBuf, srcOff, destBuff, destOff, destLen);
srcDataLen -= destLen;
srcOff += destLen;
nWritten = destLen;
return nWritten;
- }
- else
- {
+ } else {
Array.Copy(srcBuf, srcOff, destBuff, destOff, srcDataLen);
nWritten = srcDataLen;
srcDataLen = 0;
@@ -268,158 +254,146 @@ public static int CopyData()
///
/// The literal to return
/// The received value
- internal static long Identity(long literal)
- {
- return literal;
- }
+ internal static long Identity(long literal) {
+ return literal;
+ }
- ///
- /// This method returns the literal value received
- ///
- /// The literal to return
- /// The received value
- internal static ulong Identity(ulong literal)
- {
- return literal;
- }
+ ///
+ /// This method returns the literal value received
+ ///
+ /// The literal to return
+ /// The received value
+ internal static ulong Identity(ulong literal) {
+ return literal;
+ }
- ///
- /// This method returns the literal value received
- ///
- /// The literal to return
- /// The received value
- internal static float Identity(float literal)
- {
- return literal;
- }
+ ///
+ /// This method returns the literal value received
+ ///
+ /// The literal to return
+ /// The received value
+ internal static float Identity(float literal) {
+ return literal;
+ }
- ///
- /// This method returns the literal value received
- ///
- /// The literal to return
- /// The received value
- internal static double Identity(double literal)
- {
- return literal;
- }
-
- /*******************************/
- ///
- /// Performs an unsigned bitwise right shift with the specified number
- ///
- /// Number to operate on
- /// Ammount of bits to shift
- /// The resulting number from the shift operation
- internal static int URShift(int number, int bits)
- {
- if ( number >= 0)
- return number >> bits;
- else
- return (number >> bits) + (2 << ~bits);
- }
-
- ///
- /// Performs an unsigned bitwise right shift with the specified number
- ///
- /// Number to operate on
- /// Ammount of bits to shift
- /// The resulting number from the shift operation
- internal static int URShift(int number, long bits)
- {
- return URShift(number, (int)bits);
- }
-
- ///
- /// Performs an unsigned bitwise right shift with the specified number
- ///
- /// Number to operate on
- /// Ammount of bits to shift
- /// The resulting number from the shift operation
- internal static long URShift(long number, int bits)
- {
- if ( number >= 0)
- return number >> bits;
- else
- return (number >> bits) + (2L << ~bits);
- }
-
- ///
- /// Performs an unsigned bitwise right shift with the specified number
- ///
- /// Number to operate on
- /// Ammount of bits to shift
- /// The resulting number from the shift operation
- internal static long URShift(long number, long bits)
- {
- return URShift(number, (int)bits);
- }
-
- /*******************************/
- /// Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.
- /// The source Stream to ReadPos from.
- /// Contains the array of characters ReadPos from the source Stream.
- /// The starting index of the target array.
- /// The maximum number of characters to ReadPos from the source Stream.
- /// The number of characters ReadPos. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the End of the stream is reached.
- internal static System.Int32 ReadInput(System.IO.Stream sourceStream, byte[] target, int start, int count)
- {
- // Returns 0 bytes if not enough space in target
- if (target.Length == 0)
- return 0;
-
- byte[] receiver = new byte[target.Length];
- int bytesRead = sourceStream.Read(receiver, start, count);
-
- // Returns -1 if EOF
- if (bytesRead == 0)
- return -1;
-
- for(int i = start; i < start + bytesRead; i++)
- target[i] = (byte)receiver[i];
-
- return bytesRead;
- }
-
- /// Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.
- /// The source TextReader to ReadPos from
- /// Contains the array of characteres ReadPos from the source TextReader.
- /// The starting index of the target array.
- /// The maximum number of characters to ReadPos from the source TextReader.
- /// The number of characters ReadPos. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the End of the stream is reached.
- internal static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count)
- {
- // Returns 0 bytes if not enough space in target
- if (target.Length == 0) return 0;
-
- char[] charArray = new char[target.Length];
- int bytesRead = sourceTextReader.Read(charArray, start, count);
-
- // Returns -1 if EOF
- if (bytesRead == 0) return -1;
-
- for(int index=start; index
- /// Converts a string to an array of bytes
- ///
- /// The string to be converted
- /// The new array of bytes
- internal static byte[] ToByteArray(string sourceString)
- {
- return Encoding.UTF8.GetBytes(sourceString);
- }
-
- ///
- /// Converts an array of bytes to an array of chars
- ///
- /// The array of bytes to convert
- /// The new array of chars
- internal static char[] ToCharArray(byte[] byteArray)
- {
+ ///
+ /// This method returns the literal value received
+ ///
+ /// The literal to return
+ /// The received value
+ internal static double Identity(double literal) {
+ return literal;
+ }
+
+ /*******************************/
+ ///
+ /// Performs an unsigned bitwise right shift with the specified number
+ ///
+ /// Number to operate on
+ /// Ammount of bits to shift
+ /// The resulting number from the shift operation
+ internal static int URShift(int number, int bits) {
+ if (number >= 0)
+ return number >> bits;
+ else
+ return (number >> bits) + (2 << ~bits);
+ }
+
+ ///
+ /// Performs an unsigned bitwise right shift with the specified number
+ ///
+ /// Number to operate on
+ /// Ammount of bits to shift
+ /// The resulting number from the shift operation
+ internal static int URShift(int number, long bits) {
+ return URShift(number, (int)bits);
+ }
+
+ ///
+ /// Performs an unsigned bitwise right shift with the specified number
+ ///
+ /// Number to operate on
+ /// Ammount of bits to shift
+ /// The resulting number from the shift operation
+ internal static long URShift(long number, int bits) {
+ if (number >= 0)
+ return number >> bits;
+ else
+ return (number >> bits) + (2L << ~bits);
+ }
+
+ ///
+ /// Performs an unsigned bitwise right shift with the specified number
+ ///
+ /// Number to operate on
+ /// Ammount of bits to shift
+ /// The resulting number from the shift operation
+ internal static long URShift(long number, long bits) {
+ return URShift(number, (int)bits);
+ }
+
+ /*******************************/
+ /// Reads a number of characters from the current source Stream and writes the data to the target array at the specified index.
+ /// The source Stream to ReadPos from.
+ /// Contains the array of characters ReadPos from the source Stream.
+ /// The starting index of the target array.
+ /// The maximum number of characters to ReadPos from the source Stream.
+ /// The number of characters ReadPos. The number will be less than or equal to count depending on the data available in the source Stream. Returns -1 if the End of the stream is reached.
+ internal static System.Int32 ReadInput(System.IO.Stream sourceStream, byte[] target, int start, int count) {
+ // Returns 0 bytes if not enough space in target
+ if (target.Length == 0)
+ return 0;
+
+ byte[] receiver = new byte[target.Length];
+ int bytesRead = sourceStream.Read(receiver, start, count);
+
+ // Returns -1 if EOF
+ if (bytesRead == 0)
+ return -1;
+
+ for (int i = start; i < start + bytesRead; i++)
+ target[i] = (byte)receiver[i];
+
+ return bytesRead;
+ }
+
+ /// Reads a number of characters from the current source TextReader and writes the data to the target array at the specified index.
+ /// The source TextReader to ReadPos from
+ /// Contains the array of characteres ReadPos from the source TextReader.
+ /// The starting index of the target array.
+ /// The maximum number of characters to ReadPos from the source TextReader.
+ /// The number of characters ReadPos. The number will be less than or equal to count depending on the data available in the source TextReader. Returns -1 if the End of the stream is reached.
+ internal static System.Int32 ReadInput(System.IO.TextReader sourceTextReader, byte[] target, int start, int count) {
+ // Returns 0 bytes if not enough space in target
+ if (target.Length == 0) return 0;
+
+ char[] charArray = new char[target.Length];
+ int bytesRead = sourceTextReader.Read(charArray, start, count);
+
+ // Returns -1 if EOF
+ if (bytesRead == 0) return -1;
+
+ for (int index = start; index < start + bytesRead; index++)
+ target[index] = (byte)charArray[index];
+
+ return bytesRead;
+ }
+
+ ///
+ /// Converts a string to an array of bytes
+ ///
+ /// The string to be converted
+ /// The new array of bytes
+ internal static byte[] ToByteArray(string sourceString) {
+ return Encoding.UTF8.GetBytes(sourceString);
+ }
+
+ ///
+ /// Converts an array of bytes to an array of chars
+ ///
+ /// The array of bytes to convert
+ /// The new array of chars
+ internal static char[] ToCharArray(byte[] byteArray) {
return Encoding.UTF8.GetChars(byteArray);
}
@@ -476,8 +450,8 @@ internal static char[] ToCharArray(byte[] byteArray)
///
internal const int DIST_CODE_LEN = 512;
- internal static readonly byte[] _dist_code = new byte[]{0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
- 29, 29, 29, 29, 29, 29, 29, 29, 29};
+ internal static readonly byte[] _dist_code = new byte[]{0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+ 29, 29, 29, 29, 29, 29, 29, 29, 29};
internal static readonly byte[] _length_code = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19, 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28 };
diff --git a/Src/IronPython.SQLite/Connection.cs b/Src/IronPython.SQLite/Connection.cs
index 65e5e9361..3ab5bb0ff 100644
--- a/Src/IronPython.SQLite/Connection.cs
+++ b/Src/IronPython.SQLite/Connection.cs
@@ -8,42 +8,37 @@
using System;
using System.Collections;
using System.Collections.Generic;
-using System.Runtime.InteropServices;
-using System.Threading;
+
using Community.CsharpSqlite;
+
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
+
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
using sqlite3_stmt = Community.CsharpSqlite.Sqlite3.Vdbe;
using sqlite3_value = Community.CsharpSqlite.Sqlite3.Mem;
-namespace IronPython.SQLite
-{
- public static partial class PythonSQLite
- {
+namespace IronPython.SQLite {
+ public static partial class PythonSQLite {
[PythonType]
- public class Connection
- {
+ public class Connection {
public bool autocommit = false;
public int total_changes { get { return Sqlite3.sqlite3_total_changes(this.db); } }
-
+
public int detect_types { get; set; }
public bool check_same_thread { get; set; }
private double _timeout;
- public double timeout
- {
+ public double timeout {
get { return _timeout; }
set { _timeout = value; Sqlite3.sqlite3_busy_timeout(this.db, (int)(_timeout * 1000)); }
}
private string _isolation_level;
- public string isolation_level
- {
+ public string isolation_level {
get { return _isolation_level; }
set { setIsolationLevel(value); }
}
@@ -65,7 +60,7 @@ public string isolation_level
internal bool inTransaction = false;
internal int thread_ident = Environment.CurrentManagedThreadId;
- private static readonly Dictionary emptyKwargs= new Dictionary();
+ private static readonly Dictionary emptyKwargs = new Dictionary();
public PythonType Warning = PythonSQLite.Warning;
public PythonType Error = PythonSQLite.Error;
@@ -78,23 +73,21 @@ public string isolation_level
public PythonType ProgrammingError = PythonSQLite.ProgrammingError;
public PythonType NotSupportedError = PythonSQLite.NotSupportedError;
- private enum AllStatmentsAction
- {
+ private enum AllStatmentsAction {
Reset, Finalize
}
public Connection(string database,
- double timeout=0.0,
- int detect_types=0,
- string isolation_level=null,
- bool check_same_thread=true,
- object factory=null,
- int cached_statements=0)
- {
+ double timeout = 0.0,
+ int detect_types = 0,
+ string isolation_level = null,
+ bool check_same_thread = true,
+ object factory = null,
+ int cached_statements = 0) {
this.text_factory = typeof(string);
int rc = Sqlite3.sqlite3_open(database, out this.db);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
setIsolationLevel(isolation_level ?? "");
@@ -104,150 +97,135 @@ public Connection(string database,
this.check_same_thread = check_same_thread;
}
- ~Connection()
- {
- if(this.db != null)
+ ~Connection() {
+ if (this.db != null)
Sqlite3.sqlite3_close(this.db);
}
[Documentation("Closes the connection.")]
- public void close()
- {
+ public void close() {
checkThread();
doAllStatements(AllStatmentsAction.Finalize);
- if(this.db != null)
- {
+ if (this.db != null) {
int rc = Sqlite3.SQLITE_OK, i = 0;
-
- do
- {
+
+ do {
rc = Sqlite3.sqlite3_close(this.db);
- if(rc == Sqlite3.SQLITE_BUSY)
- {
+ if (rc == Sqlite3.SQLITE_BUSY) {
GC.Collect();
GC.WaitForPendingFinalizers();
}
- } while(rc == Sqlite3.SQLITE_BUSY && i++ < 3);
+ } while (rc == Sqlite3.SQLITE_BUSY && i++ < 3);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
this.db = null;
}
}
- internal void begin()
- {
+ internal void begin() {
sqlite3_stmt statement = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, this.begin_statement, -1, ref statement, ref tail);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, statement);
rc = Util.Step(statement);
- if(rc == Sqlite3.SQLITE_DONE)
+ if (rc == Sqlite3.SQLITE_DONE)
this.inTransaction = true;
else
throw GetSqliteError(this.db, statement);
rc = Sqlite3.sqlite3_finalize(statement);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
GetSqliteError(this.db, null);
}
[Documentation("Commit the current transaction.")]
- public void commit()
- {
+ public void commit() {
checkThread(); checkConnection();
- if(inTransaction)
- {
+ if (inTransaction) {
sqlite3_stmt statement = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, "COMMIT", -1, ref statement, ref tail);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
rc = Util.Step(statement);
- if(rc == Sqlite3.SQLITE_DONE)
+ if (rc == Sqlite3.SQLITE_DONE)
this.inTransaction = false;
else
throw GetSqliteError(this.db, statement);
rc = Sqlite3.sqlite3_finalize(statement);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
GetSqliteError(this.db, null);
}
}
[Documentation("Roll back the current transaction.")]
- public void rollback()
- {
+ public void rollback() {
checkThread(); checkConnection();
- if(inTransaction)
- {
+ if (inTransaction) {
doAllStatements(AllStatmentsAction.Reset);
sqlite3_stmt statement = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, "ROLLBACK", -1, ref statement, ref tail);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.db, null);
rc = Util.Step(statement);
- if(rc == Sqlite3.SQLITE_DONE)
+ if (rc == Sqlite3.SQLITE_DONE)
this.inTransaction = false;
else
throw GetSqliteError(this.db, statement);
rc = Sqlite3.sqlite3_finalize(statement);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
GetSqliteError(this.db, null);
}
}
[Documentation("Return a cursor for the connection.")]
- public object cursor(CodeContext context, object factory=null)
- {
+ public object cursor(CodeContext context, object factory = null) {
checkThread(); checkConnection();
object cursor = factory == null ? new Cursor(context, this) : PythonCalls.Call(context, factory, this);
- if(this.row_factory != null)
+ if (this.row_factory != null)
context.LanguageContext.Operations.SetMember(cursor, "row_factory", this.row_factory);
return cursor;
}
[Documentation("Executes a SQL statement. Non-standard.")]
- public object execute(CodeContext context, [ParamDictionary]IDictionary kwargs, params object[] args)
- {
+ public object execute(CodeContext context, [ParamDictionary] IDictionary kwargs, params object[] args) {
object c = cursor(context, null);
object execute = context.LanguageContext.Operations.GetMember(c, "execute");
return PythonCalls.CallWithKeywordArgs(context, execute, args, kwargs);
}
[Documentation("Repeatedly executes a SQL statement. Non-standard.")]
- public object executemany(CodeContext context, [ParamDictionary]IDictionary kwargs, params object[] args)
- {
+ public object executemany(CodeContext context, [ParamDictionary] IDictionary kwargs, params object[] args) {
object c = cursor(context, null);
object executemany = context.LanguageContext.Operations.GetMember(c, "executemany");
return PythonCalls.CallWithKeywordArgs(context, executemany, args, kwargs);
}
[Documentation("Executes a multiple SQL statements at once. Non-standard.")]
- public object executescript(CodeContext context, [ParamDictionary]IDictionary kwargs, params object[] args)
- {
+ public object executescript(CodeContext context, [ParamDictionary] IDictionary kwargs, params object[] args) {
object c = cursor(context, null);
object executescript = context.LanguageContext.Operations.GetMember(c, "executescript");
return PythonCalls.CallWithKeywordArgs(context, executescript, args, kwargs);
}
- public object __call__(string sql)
- {
+ public object __call__(string sql) {
dropUnusedStatementReferences();
Statement statement = new Statement(this, sql);
@@ -255,17 +233,16 @@ public object __call__(string sql)
return statement;
}
- private void dropUnusedStatementReferences()
- {
- if(this.created_statements++ < 200)
+ private void dropUnusedStatementReferences() {
+ if (this.created_statements++ < 200)
return;
this.created_statements = 0;
List new_list = new List();
- foreach(WeakReference weakref in this.statements)
- if(weakref.IsAlive)
+ foreach (WeakReference weakref in this.statements)
+ if (weakref.IsAlive)
new_list.Add(weakref);
this.statements = new_list;
@@ -274,51 +251,43 @@ private void dropUnusedStatementReferences()
#region User functions
[Documentation("Creates a new function. Non-standard.")]
- public void create_function(CodeContext context, string name, int narg, object func)
- {
- int rc = Sqlite3.sqlite3_create_function(this.db,
- name, narg,
- Sqlite3.SQLITE_ANY,
- new object[] { context, func },
- callUserFunction,
+ public void create_function(CodeContext context, string name, int narg, object func) {
+ int rc = Sqlite3.sqlite3_create_function(this.db,
+ name, narg,
+ Sqlite3.SQLITE_ANY,
+ new object[] { context, func },
+ callUserFunction,
null, null);
-
- if(rc != Sqlite3.SQLITE_OK)
+
+ if (rc != Sqlite3.SQLITE_OK)
throw MakeOperationalError("Error creating function");
else
this.function_pinboard[func] = null;
}
- private static void callUserFunction(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] argv)
- {
+ private static void callUserFunction(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] argv) {
object[] data = (object[])Sqlite3.sqlite3_user_data(ctx);
CodeContext context = (CodeContext)data[0];
object func = data[1];
object[] args = buildPyParams(context, ctx, argc, argv);
- try
- {
+ try {
object result = PythonCalls.CallWithKeywordArgs(context, func, args, emptyKwargs);
setResult(ctx, result);
- }
- catch(Exception)
- {
+ } catch (Exception) {
Sqlite3.sqlite3_result_error(ctx, "user-defined function raised exception", -1);
}
}
- private static object[] buildPyParams(CodeContext context, Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] argv)
- {
+ private static object[] buildPyParams(CodeContext context, Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] argv) {
object[] args = new object[argc];
- for(int i = 0; i < argc; ++i)
- {
+ for (int i = 0; i < argc; ++i) {
sqlite3_value cur_value = argv[i];
object cur_py_value = null;
- switch(Sqlite3.sqlite3_value_type(cur_value))
- {
+ switch (Sqlite3.sqlite3_value_type(cur_value)) {
case Sqlite3.SQLITE_INTEGER:
cur_py_value = (int)Sqlite3.sqlite3_value_int64(cur_value);
break;
@@ -347,32 +316,28 @@ private static object[] buildPyParams(CodeContext context, Sqlite3.sqlite3_conte
return args;
}
- private static void setResult(Sqlite3.sqlite3_context ctx, object result)
- {
- if(result == null)
+ private static void setResult(Sqlite3.sqlite3_context ctx, object result) {
+ if (result == null)
Sqlite3.sqlite3_result_null(ctx);
- else if(result is bool)
+ else if (result is bool)
Sqlite3.sqlite3_result_int64(ctx, ((bool)result) ? 1 : 0);
- else if(result is int)
+ else if (result is int)
Sqlite3.sqlite3_result_int64(ctx, (int)result);
- else if(result is long)
+ else if (result is long)
Sqlite3.sqlite3_result_int64(ctx, (long)result);
else if (result is System.Numerics.BigInteger)
Sqlite3.sqlite3_result_int64(ctx, (long)(System.Numerics.BigInteger)result);
- else if(result is float)
+ else if (result is float)
Sqlite3.sqlite3_result_double(ctx, (float)result);
- else if(result is double)
+ else if (result is double)
Sqlite3.sqlite3_result_double(ctx, (double)result);
- else if(result is string)
+ else if (result is string)
Sqlite3.sqlite3_result_text(ctx, (string)result, -1, Sqlite3.SQLITE_TRANSIENT);
- else if(result is byte[])
- {
+ else if (result is byte[]) {
byte[] b = (byte[])result;
string s = Latin1.GetString(b, 0, b.Length);
Sqlite3.sqlite3_result_blob(ctx, s, s.Length, Sqlite3.SQLITE_TRANSIENT);
- }
- else
- {
+ } else {
// TODO raise error
}
}
@@ -381,58 +346,44 @@ private static void setResult(Sqlite3.sqlite3_context ctx, object result)
#region User aggregates
- private class UserAggregateThunk
- {
- public UserAggregateThunk(CodeContext context, string name, object aggregate_class)
- {
+ private class UserAggregateThunk {
+ public UserAggregateThunk(CodeContext context, string name, object aggregate_class) {
this.context = context;
this.aggregate_class = aggregate_class;
this.name = name;
}
- public void stepCallback(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] param)
- {
- if(instance == null)
- {
- try
- {
+ public void stepCallback(Sqlite3.sqlite3_context ctx, int argc, sqlite3_value[] param) {
+ if (instance == null) {
+ try {
instance = PythonCalls.Call(context, aggregate_class);
- }
- catch(Exception)
- {
+ } catch (Exception) {
Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's '__init__' method raised error", -1);
return;
}
}
- try
- {
+ try {
object step = context.LanguageContext.Operations.GetMember(instance, "step");
object[] args = buildPyParams(context, ctx, argc, param);
PythonCalls.CallWithKeywordArgs(context, step, args, new Dictionary());
- }
- catch(Exception e)
- {
- if(e is MissingMemberException)
+ } catch (Exception e) {
+ if (e is MissingMemberException)
throw;
Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's 'step' method raised error", -1);
}
}
- public void finalCallback(Sqlite3.sqlite3_context ctx)
- {
- if(instance == null)
+ public void finalCallback(Sqlite3.sqlite3_context ctx) {
+ if (instance == null)
return;
- try
- {
+ try {
object function_result = context.LanguageContext.Operations.InvokeMember(instance, "finalize");
setResult(ctx, function_result);
- }
- catch(Exception)
- {
+ } catch (Exception) {
Sqlite3.sqlite3_result_error(ctx, "user-defined aggregate's 'finalize' method raised error", -1);
}
}
@@ -444,8 +395,7 @@ public void finalCallback(Sqlite3.sqlite3_context ctx)
}
[Documentation("Creates a new aggregate. Non-standard.")]
- public void create_aggregate(CodeContext context, string name, int n_arg, object aggregate_class)
- {
+ public void create_aggregate(CodeContext context, string name, int n_arg, object aggregate_class) {
UserAggregateThunk thunk = new UserAggregateThunk(context, name, aggregate_class);
int rc = Sqlite3.sqlite3_create_function(this.db,
@@ -456,7 +406,7 @@ public void create_aggregate(CodeContext context, string name, int n_arg, object
thunk.stepCallback,
thunk.finalCallback);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw MakeOperationalError("Error creating aggregate");
else
this.function_pinboard[aggregate_class] = null;
@@ -465,45 +415,37 @@ public void create_aggregate(CodeContext context, string name, int n_arg, object
#endregion
[Documentation("Creates a collation function. Non-standard.")]
- public void create_collation(params object[] args)
- {
+ public void create_collation(params object[] args) {
throw new NotImplementedException();
}
[Documentation("Sets progress handler callback. Non-standard.")]
- public void set_progress_handler(params object[] args)
- {
+ public void set_progress_handler(params object[] args) {
throw new NotImplementedException();
}
[Documentation("Sets authorizer callback. Non-standard.")]
- public void set_authorizer(params object[] args)
- {
+ public void set_authorizer(params object[] args) {
throw new NotImplementedException();
}
[Documentation("For context manager. Non-standard.")]
- public object __enter__()
- {
+ public object __enter__() {
return this;
}
[Documentation("For context manager. Non-standard.")]
- public object __exit__(CodeContext context, object exc_type, object exc_value, object exc_tb)
- {
+ public object __exit__(CodeContext context, object exc_type, object exc_value, object exc_tb) {
DynamicOperations ops = context.LanguageContext.Operations;
- if(exc_type == null && exc_value == null && exc_tb == null)
- {
+ if (exc_type == null && exc_value == null && exc_tb == null) {
object commitfn;
- if(ops.TryGetMember(this, "commit", out commitfn))
+ if (ops.TryGetMember(this, "commit", out commitfn))
ops.Invoke(commitfn);
else
commit();
- }
- else
- {
+ } else {
object rollbackfn;
- if(ops.TryGetMember(this, "rollback", out rollbackfn))
+ if (ops.TryGetMember(this, "rollback", out rollbackfn))
ops.Invoke(rollbackfn);
else
rollback();
@@ -512,77 +454,64 @@ public object __exit__(CodeContext context, object exc_type, object exc_value, o
return false;
}
- public object iterdump(CodeContext context)
- {
+ public object iterdump(CodeContext context) {
throw new NotImplementedException("Not supported with C#-sqlite for unknown reasons.");
//var ops = context.LanguageContext.Operations;
//PythonModule sqlite3 = Importer.ImportModule(context, context.GlobalScope, "sqlite3", false, -1) as PythonModule;
//PythonModule dump = Importer.ImportFrom(context, sqlite3, "dump") as PythonModule;
-
+
//object _iterdump = ops.GetMember(dump, "_iterdump");
//object result = ops.Invoke(_iterdump, this);
//return result;
}
- internal void checkConnection()
- {
- if(this.db == null)
+ internal void checkConnection() {
+ if (this.db == null)
throw MakeProgrammingError("Cannot operate on a closed database.");
}
- internal void checkThread()
- {
- if(this.check_same_thread)
- if(this.thread_ident != Environment.CurrentManagedThreadId)
+ internal void checkThread() {
+ if (this.check_same_thread)
+ if (this.thread_ident != Environment.CurrentManagedThreadId)
throw MakeProgrammingError("SQLite objects created in a thread can only be used in that same thread." +
"The object was created in thread id {0} and this is thread id {1}".Format(
this.thread_ident, Environment.CurrentManagedThreadId));
}
- internal static void verify(Connection connection)
- {
+ internal static void verify(Connection connection) {
verify(connection, false);
}
- internal static void verify(Connection connection, bool closed)
- {
- if(!closed && (connection == null || connection.db == null))
+ internal static void verify(Connection connection, bool closed) {
+ if (!closed && (connection == null || connection.db == null))
throw MakeProgrammingError("Cannot operate on a closed database.");
connection.checkThread();
}
- private void setIsolationLevel(string isolation_level)
- {
+ private void setIsolationLevel(string isolation_level) {
this.begin_statement = null;
- if(isolation_level == null)
- {
+ if (isolation_level == null) {
this._isolation_level = null;
this.commit();
this.inTransaction = false;
- }
- else
- {
+ } else {
this._isolation_level = isolation_level;
this.begin_statement = "BEGIN " + isolation_level;
}
}
- private void doAllStatements(AllStatmentsAction action)
- {
- foreach(WeakReference weakref in this.statements)
- {
- if(weakref.IsAlive)
- {
+ private void doAllStatements(AllStatmentsAction action) {
+ foreach (WeakReference weakref in this.statements) {
+ if (weakref.IsAlive) {
Statement statement = weakref.Target as Statement;
- if(statement != null)
- {
- if(action == AllStatmentsAction.Reset)
+ if (statement != null) {
+ if (action == AllStatmentsAction.Reset)
statement.Reset();
else
statement.SqliteFinalize();
diff --git a/Src/IronPython.SQLite/Contants.cs b/Src/IronPython.SQLite/Contants.cs
index f3fe63263..ad65e4f3e 100644
--- a/Src/IronPython.SQLite/Contants.cs
+++ b/Src/IronPython.SQLite/Contants.cs
@@ -7,10 +7,8 @@
using Community.CsharpSqlite;
-namespace IronPython.SQLite
-{
- public static partial class PythonSQLite
- {
+namespace IronPython.SQLite {
+ public static partial class PythonSQLite {
public const int SQLITE_OK = Sqlite3.SQLITE_OK;
public const int SQLITE_DENY = 1;
diff --git a/Src/IronPython.SQLite/Cursor.cs b/Src/IronPython.SQLite/Cursor.cs
index 8570ad7ef..4d90c8770 100644
--- a/Src/IronPython.SQLite/Cursor.cs
+++ b/Src/IronPython.SQLite/Cursor.cs
@@ -9,24 +9,22 @@
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
-using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
+
using Community.CsharpSqlite;
+
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
+
using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
using sqlite3_stmt = Community.CsharpSqlite.Sqlite3.Vdbe;
-namespace IronPython.SQLite
-{
- public static partial class PythonSQLite
- {
+namespace IronPython.SQLite {
+ public static partial class PythonSQLite {
[PythonType]
- public class Cursor : IEnumerable
- {
+ public class Cursor : IEnumerable {
public const string __doc__ = "SQLite database cursor class.";
private Statement statement;
@@ -40,9 +38,8 @@ public class Cursor : IEnumerable
public int rowcount { get; private set; }
- public int? rownumber
- {
- get { return null; }
+ public int? rownumber {
+ get { return null; }
}
public BigInteger? lastrowid { get; private set; }
@@ -53,62 +50,54 @@ public int? rownumber
public Connection connection { get; private set; }
- public object callproc(string procname)
- {
+ public object callproc(string procname) {
throw PythonSQLite.MakeNotSupportedError();
}
private CodeContext context;
- public Cursor(CodeContext context, Connection connection)
- {
+ public Cursor(CodeContext context, Connection connection) {
this.context = context;
this.connection = connection;
this.arraysize = 1;
this.rowcount = -1;
- if(this.connection != null)
+ if (this.connection != null)
this.connection.checkThread();
}
- ~Cursor()
- {
- if(this.statement != null)
+ ~Cursor() {
+ if (this.statement != null)
this.statement.Reset();
}
[Documentation("Closes the cursor.")]
- public void close()
- {
+ public void close() {
connection.checkThread(); connection.checkConnection();
- if(this.statement != null)
- {
+ if (this.statement != null) {
this.statement.Reset();
}
}
[Documentation("Executes a SQL statement.")]
- public object execute(CodeContext context, object operation, object args=null)
- {
+ public object execute(CodeContext context, object operation, object args = null) {
return queryExecute(context, false, operation, args);
}
[Documentation("Repeatedly executes a SQL statement.")]
- public object executemany(CodeContext context, object operation, object args)
- {
+ public object executemany(CodeContext context, object operation, object args) {
return queryExecute(context, true, operation, args);
}
- private object queryExecute(CodeContext context, bool multiple, object operation_obj, object args)
- {
- if(!(operation_obj is string))
+ private object queryExecute(CodeContext context, bool multiple, object operation_obj, object args) {
+ if (!(operation_obj is string))
throw CreateThrowable(PythonExceptions.ValueError, "operation parameter must be str or unicode");
string operation = (string)operation_obj;
- if(string.IsNullOrEmpty(operation))
+ if (string.IsNullOrEmpty(operation))
return null;
int rc;
@@ -118,21 +107,18 @@ private object queryExecute(CodeContext context, bool multiple, object operation
this.next_row = null;
IEnumerator parameters_iter = null;
- if(multiple)
- {
- if(args != null)
+ if (multiple) {
+ if (args != null)
parameters_iter = PythonOps.CreatePythonEnumerator(context, args);
- }
- else
- {
+ } else {
object[] parameters_list = { args };
- if(parameters_list[0] == null)
+ if (parameters_list[0] == null)
parameters_list[0] = new PythonTuple();
parameters_iter = parameters_list.GetEnumerator();
}
- if(this.statement != null)
+ if (this.statement != null)
rc = this.statement.Reset();
this.description = null;
@@ -141,35 +127,33 @@ private object queryExecute(CodeContext context, bool multiple, object operation
// TODO: use stmt cache instead ?
this.statement = (Statement)this.connection.__call__(operation);
- if(this.statement.in_use)
+ if (this.statement.in_use)
this.statement = new Statement(connection, operation);
this.statement.Reset();
this.statement.MarkDirty();
- if(!string.IsNullOrEmpty(connection.begin_statement))
- {
- switch(statement.StatementType)
- {
+ if (!string.IsNullOrEmpty(connection.begin_statement)) {
+ switch (statement.StatementType) {
case StatementType.Update:
case StatementType.Insert:
case StatementType.Delete:
case StatementType.Replace:
- if(!connection.inTransaction)
+ if (!connection.inTransaction)
connection.begin();
-
+
break;
case StatementType.Other:
// it's a DDL statement or something similar
// we better COMMIT first so it works for all cases
- if(connection.inTransaction)
+ if (connection.inTransaction)
connection.commit();
break;
case StatementType.Select:
- if(multiple)
+ if (multiple)
throw MakeProgrammingError("You cannot execute SELECT statements in executemany().");
break;
@@ -178,9 +162,8 @@ private object queryExecute(CodeContext context, bool multiple, object operation
}
}
- while(true)
- {
- if(!parameters_iter.MoveNext())
+ while (true) {
+ if (!parameters_iter.MoveNext())
break;
object parameters = parameters_iter.Current;
@@ -188,45 +171,35 @@ private object queryExecute(CodeContext context, bool multiple, object operation
this.statement.MarkDirty();
this.statement.BindParameters(context, parameters);
- while(true)
- {
+ while (true) {
rc = this.statement.RawStep();
- if(rc == Sqlite3.SQLITE_DONE || rc == Sqlite3.SQLITE_ROW)
+ if (rc == Sqlite3.SQLITE_DONE || rc == Sqlite3.SQLITE_ROW)
break;
rc = this.statement.Reset();
- if(rc == Sqlite3.SQLITE_SCHEMA)
- {
+ if (rc == Sqlite3.SQLITE_SCHEMA) {
rc = this.statement.Recompile(context, parameters);
- if(rc == Sqlite3.SQLITE_OK)
- {
+ if (rc == Sqlite3.SQLITE_OK) {
continue;
- }
- else
- {
+ } else {
this.statement.Reset();
throw GetSqliteError(this.connection.db, null);
}
- }
- else
- {
+ } else {
this.statement.Reset();
throw GetSqliteError(this.connection.db, null);
}
}
- if(!buildRowCastMap())
+ if (!buildRowCastMap())
throw MakeOperationalError("Error while building row_cast_map");
- if(rc == Sqlite3.SQLITE_ROW || (rc == Sqlite3.SQLITE_DONE && this.statement.StatementType == StatementType.Select))
- {
- if(this.description == null)
- {
+ if (rc == Sqlite3.SQLITE_ROW || (rc == Sqlite3.SQLITE_DONE && this.statement.StatementType == StatementType.Select)) {
+ if (this.description == null) {
int numcols = Sqlite3.sqlite3_column_count(this.statement.st);
object[] new_description = new object[numcols];
- for(int i = 0; i < numcols; ++i)
- {
+ for (int i = 0; i < numcols; ++i) {
string name = buildColumnName(Sqlite3.sqlite3_column_name(this.statement.st, i));
object descriptor = new object[] {
@@ -246,98 +219,78 @@ private object queryExecute(CodeContext context, bool multiple, object operation
}
}
- if(rc == Sqlite3.SQLITE_ROW)
- {
- if(multiple)
+ if (rc == Sqlite3.SQLITE_ROW) {
+ if (multiple)
throw MakeProgrammingError("executemany() can only execute DML statements.");
this.next_row = fetchOneRow(context);
- }
- else if(rc == Sqlite3.SQLITE_DONE && !multiple)
- {
+ } else if (rc == Sqlite3.SQLITE_DONE && !multiple) {
this.statement.Reset();
}
- switch(this.statement.StatementType)
- {
+ switch (this.statement.StatementType) {
case StatementType.Update:
case StatementType.Delete:
case StatementType.Insert:
case StatementType.Replace:
- if(this.rowcount == -1)
+ if (this.rowcount == -1)
this.rowcount = 0;
this.rowcount += Sqlite3.sqlite3_changes(this.connection.db);
break;
}
- if(!multiple && this.statement.StatementType == StatementType.Insert)
- {
+ if (!multiple && this.statement.StatementType == StatementType.Insert) {
this.lastrowid = Sqlite3.sqlite3_last_insert_rowid(this.connection.db);
- }
- else
- {
+ } else {
this.lastrowid = null;
}
- if(multiple)
+ if (multiple)
rc = this.statement.Reset();
}
return this;
}
- private string buildColumnName(string colname)
- {
+ private string buildColumnName(string colname) {
int n = colname.IndexOf('[');
return n < 0 ? colname : colname.Substring(0, n).Trim();
}
- private object fetchOneRow(CodeContext context)
- {
+ private object fetchOneRow(CodeContext context) {
int numcols = Sqlite3.sqlite3_data_count(this.statement.st);
object[] row = new object[numcols];
object converter = null;
- for(int i = 0; i < numcols; ++i)
- {
+ for (int i = 0; i < numcols; ++i) {
object converted = null;
- if(this.connection.detect_types != 0)
- {
+ if (this.connection.detect_types != 0) {
converter = row_cast_map[i];
- }
- else
- {
+ } else {
converter = null;
}
- if(converter != null)
- {
+ if (converter != null) {
byte[] val = Sqlite3.sqlite3_column_blob(this.statement.st, i);
- if(val == null)
- {
+ if (val == null) {
converted = null;
- }
- else
- {
+ } else {
string item = Latin1.GetString(val, 0, val.Length);
converted = PythonCalls.Call(context, converter, item);
}
- }
- else
- {
+ } else {
int coltype = Sqlite3.sqlite3_column_type(this.statement.st, i);
- switch(coltype)
- {
+ switch (coltype) {
case Sqlite3.SQLITE_NULL:
converted = null;
break;
case Sqlite3.SQLITE_INTEGER:
long l = Sqlite3.sqlite3_column_int64(this.statement.st, i);
- if(l < int.MinValue || l > int.MaxValue)
+ if (l < int.MinValue || l > int.MaxValue)
converted = (BigInteger)l;
else
converted = (int)l;
@@ -365,8 +318,7 @@ private object fetchOneRow(CodeContext context)
return new PythonTuple(row);
}
- public Cursor executescript(string operation)
- {
+ public Cursor executescript(string operation) {
connection.checkThread(); connection.checkConnection();
this.connection.commit();
@@ -374,9 +326,8 @@ public Cursor executescript(string operation)
sqlite3_stmt statement = null;
string script = operation;
bool statement_completed = false;
- while(true)
- {
- if(Sqlite3.sqlite3_complete(operation) == 0)
+ while (true) {
+ if (Sqlite3.sqlite3_complete(operation) == 0)
break;
statement_completed = true;
@@ -386,46 +337,41 @@ public Cursor executescript(string operation)
ref statement,
ref script);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.connection.db, null);
/* execute statement, and ignore results of SELECT statements */
rc = Sqlite3.SQLITE_ROW;
- while(rc == Sqlite3.SQLITE_ROW)
+ while (rc == Sqlite3.SQLITE_ROW)
rc = Sqlite3.sqlite3_step(statement);
- if(rc != Sqlite3.SQLITE_DONE)
- {
+ if (rc != Sqlite3.SQLITE_DONE) {
Sqlite3.sqlite3_finalize(statement);
throw GetSqliteError(this.connection.db, null);
}
rc = Sqlite3.sqlite3_finalize(statement);
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw GetSqliteError(this.connection.db, null);
}
- if(!statement_completed)
+ if (!statement_completed)
throw MakeProgrammingError("you did not provide a complete SQL statement");
return this;
}
- public object __iter__()
- {
+ public object __iter__() {
return this;
}
- public object __next__(CodeContext context)
- {
+ public object __next__(CodeContext context) {
object next_row_tuple, next_row;
connection.checkThread(); connection.checkConnection();
- if(this.next_row == null)
- {
- if(this.statement != null)
- {
+ if (this.next_row == null) {
+ if (this.statement != null) {
this.statement.Reset();
this.statement = null;
}
@@ -436,25 +382,20 @@ public object __next__(CodeContext context)
next_row_tuple = this.next_row;
this.next_row = null;
- if(this.row_factory != null)
- {
+ if (this.row_factory != null) {
next_row = PythonCalls.Call(context, this.row_factory, this, next_row_tuple);
- }
- else
- {
+ } else {
next_row = next_row_tuple;
}
- if(this.statement != null)
- {
+ if (this.statement != null) {
int rc = this.statement.RawStep();
- if(rc != Sqlite3.SQLITE_DONE && rc != Sqlite3.SQLITE_ROW)
- {
+ if (rc != Sqlite3.SQLITE_DONE && rc != Sqlite3.SQLITE_ROW) {
this.statement.Reset();
throw GetSqliteError(this.connection.db, this.statement.st);
}
- if(rc == Sqlite3.SQLITE_ROW)
+ if (rc == Sqlite3.SQLITE_ROW)
this.next_row = fetchOneRow(context);
}
@@ -462,41 +403,33 @@ public object __next__(CodeContext context)
}
[Documentation("Fetches one row from the resultset.")]
- public object fetchone(CodeContext context)
- {
- try
- {
+ public object fetchone(CodeContext context) {
+ try {
return this.__next__(context);
- }
- catch(StopIterationException)
- {
+ } catch (StopIterationException) {
return null;
}
}
- public object fetchmany(CodeContext context)
- {
+ public object fetchmany(CodeContext context) {
return fetchmany(context, this.arraysize);
}
[Documentation("Fetches several rows from the resultset.")]
- public object fetchmany(CodeContext context, int size)
- {
+ public object fetchmany(CodeContext context, int size) {
PythonList result = new PythonList();
object item = fetchone(context);
- for(int i = 0; i < size && item != null; ++i, item = fetchone(context))
+ for (int i = 0; i < size && item != null; ++i, item = fetchone(context))
result.Add(item);
return result;
}
[Documentation("Fetches all rows from the resultset.")]
- public object fetchall(CodeContext context)
- {
+ public object fetchall(CodeContext context) {
PythonList result = new PythonList();
object item = fetchone(context);
- while(item != null)
- {
+ while (item != null) {
result.Add(item);
item = fetchone(context);
}
@@ -504,8 +437,7 @@ public object fetchall(CodeContext context)
return result;
}
- public object nextset()
- {
+ public object nextset() {
return null;
}
@@ -515,42 +447,34 @@ public void setinputsizes(object sizes) { }
[Documentation("Required by DB-API. Does nothing in IronPython.Sqlite3.")]
public void setoutputsize(params object[] args) { }
- private bool buildRowCastMap()
- {
- if(this.connection.detect_types == 0)
+ private bool buildRowCastMap() {
+ if (this.connection.detect_types == 0)
return true;
row_cast_map = new List();
object converter = null;
- for(int i = 0; i < Sqlite3.sqlite3_column_count(this.statement.st); ++i)
- {
+ for (int i = 0; i < Sqlite3.sqlite3_column_count(this.statement.st); ++i) {
converter = null;
- if((this.connection.detect_types & PARSE_COLNAMES) != 0)
- {
+ if ((this.connection.detect_types & PARSE_COLNAMES) != 0) {
string colname = Sqlite3.sqlite3_column_name(this.statement.st, i);
- if(colname != null)
- {
+ if (colname != null) {
Regex matchColname = new Regex(@"\[(\w+)\]");
Match match = matchColname.Match(colname);
- if(match.Success)
- {
+ if (match.Success) {
string key = match.Groups[1].ToString();
converter = getConverter(key);
}
}
}
- if((converter == null) && ((this.connection.detect_types & PARSE_DECLTYPES) != 0))
- {
+ if ((converter == null) && ((this.connection.detect_types & PARSE_DECLTYPES) != 0)) {
string decltype = Sqlite3.sqlite3_column_decltype(this.statement.st, i);
- if(decltype != null)
- {
+ if (decltype != null) {
Regex matchDecltype = new Regex(@"\b(\w+)\b");
Match match = matchDecltype.Match(decltype);
- if(match.Success)
- {
+ if (match.Success) {
string py_decltype = match.Groups[1].ToString();
converter = getConverter(py_decltype);
}
@@ -563,23 +487,19 @@ private bool buildRowCastMap()
return true;
}
- private object getConverter(string key)
- {
+ private object getConverter(string key) {
object converter;
return converters.TryGetValue(key.ToUpperInvariant(), out converter) ? converter : null;
}
#region IEnumerable Members
- public IEnumerator GetEnumerator()
- {
+ public IEnumerator GetEnumerator() {
PythonList results = new PythonList();
- try
- {
- while(true)
+ try {
+ while (true)
results.append(this.__next__(this.context));
- }
- catch(StopIterationException) { }
+ } catch (StopIterationException) { }
return results.GetEnumerator();
}
diff --git a/Src/IronPython.SQLite/Exceptions.cs b/Src/IronPython.SQLite/Exceptions.cs
index 99117ae47..978cf76e6 100644
--- a/Src/IronPython.SQLite/Exceptions.cs
+++ b/Src/IronPython.SQLite/Exceptions.cs
@@ -6,18 +6,17 @@
//
using System;
+
using Community.CsharpSqlite;
+
using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
-namespace IronPython.SQLite
-{
- public static partial class PythonSQLite
- {
- private static void InitModuleExceptions(PythonContext context, PythonDictionary dict)
- {
+namespace IronPython.SQLite {
+ public static partial class PythonSQLite {
+ private static void InitModuleExceptions(PythonContext context, PythonDictionary dict) {
Warning = context.EnsureModuleException("sqlite.Warning", PythonExceptions.Warning, dict, "Warning", "_sqlite3");
Error = context.EnsureModuleException("sqlite.Error", PythonExceptions.Exception, dict, "Error", "_sqlite3");
InterfaceError = context.EnsureModuleException("sqlite.InterfaceError", Error, dict, "InterfaceError", "_sqlite3");
@@ -31,78 +30,65 @@ private static void InitModuleExceptions(PythonContext context, PythonDictionary
}
public static PythonType Warning;
- internal static Exception MakeWarning(params object[] args)
- {
+ internal static Exception MakeWarning(params object[] args) {
return CreateThrowable(Warning, args);
}
public static PythonType Error;
- internal static Exception MakeError(params object[] args)
- {
+ internal static Exception MakeError(params object[] args) {
return CreateThrowable(Error, args);
}
public static PythonType InterfaceError;
- internal static Exception MakeInterfaceError(params object[] args)
- {
+ internal static Exception MakeInterfaceError(params object[] args) {
return CreateThrowable(InterfaceError, args);
}
public static PythonType DatabaseError;
- internal static Exception MakeDatabaseError(params object[] args)
- {
+ internal static Exception MakeDatabaseError(params object[] args) {
return CreateThrowable(DatabaseError, args);
}
public static PythonType DataError;
- internal static Exception MakeDataError(params object[] args)
- {
+ internal static Exception MakeDataError(params object[] args) {
return CreateThrowable(DataError, args);
}
public static PythonType OperationalError;
- internal static Exception MakeOperationalError(params object[] args)
- {
+ internal static Exception MakeOperationalError(params object[] args) {
return CreateThrowable(OperationalError, args);
}
public static PythonType IntegrityError;
- internal static Exception MakeIntegrityError(params object[] args)
- {
+ internal static Exception MakeIntegrityError(params object[] args) {
return CreateThrowable(IntegrityError, args);
}
public static PythonType InternalError;
- internal static Exception MakeInternalError(params object[] args)
- {
+ internal static Exception MakeInternalError(params object[] args) {
return CreateThrowable(InternalError, args);
}
public static PythonType ProgrammingError;
- internal static Exception MakeProgrammingError(params object[] args)
- {
+ internal static Exception MakeProgrammingError(params object[] args) {
return CreateThrowable(ProgrammingError, args);
}
public static PythonType NotSupportedError;
- internal static Exception MakeNotSupportedError(params object[] args)
- {
+ internal static Exception MakeNotSupportedError(params object[] args) {
return CreateThrowable(NotSupportedError, args);
}
- internal static Exception GetSqliteError(Sqlite3.sqlite3 db, Sqlite3.Vdbe st)
- {
+ internal static Exception GetSqliteError(Sqlite3.sqlite3 db, Sqlite3.Vdbe st) {
/* SQLite often doesn't report anything useful, unless you reset the statement first */
- if(st != null)
- {
+ if (st != null) {
Sqlite3.sqlite3_reset(st);
}
int errorcode = Sqlite3.sqlite3_errcode(db);
string errmsg = Sqlite3.sqlite3_errmsg(db);
- switch(errorcode)
- {
+ switch (errorcode) {
case SQLITE_OK:
return null;
@@ -146,8 +132,7 @@ internal static Exception GetSqliteError(Sqlite3.sqlite3 db, Sqlite3.Vdbe st)
}
}
- private static Exception CreateThrowable(PythonType type, params object[] args)
- {
+ private static Exception CreateThrowable(PythonType type, params object[] args) {
return PythonOps.CreateThrowable(type, args);
}
}
diff --git a/Src/IronPython.SQLite/Extensions.cs b/Src/IronPython.SQLite/Extensions.cs
index 40c1cf389..2f556d5e1 100644
--- a/Src/IronPython.SQLite/Extensions.cs
+++ b/Src/IronPython.SQLite/Extensions.cs
@@ -5,17 +5,13 @@
// Copyright (c) Jeff Hardy 2010-2012.
//
-namespace IronPython.SQLite
-{
- internal static class StringExtensions
- {
- public static string Format(this string format, params object[] args)
- {
+namespace IronPython.SQLite {
+ internal static class StringExtensions {
+ public static string Format(this string format, params object[] args) {
return string.Format(format, args);
}
- public static bool IsNullOrEmpty(this string value)
- {
+ public static bool IsNullOrEmpty(this string value) {
return string.IsNullOrEmpty(value);
}
}
diff --git a/Src/IronPython.SQLite/Properties/AssemblyInfo.cs b/Src/IronPython.SQLite/Properties/AssemblyInfo.cs
index e1fc294d1..78ec08d19 100644
--- a/Src/IronPython.SQLite/Properties/AssemblyInfo.cs
+++ b/Src/IronPython.SQLite/Properties/AssemblyInfo.cs
@@ -1,5 +1,4 @@
using System.Reflection;
-using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
diff --git a/Src/IronPython.SQLite/Row.cs b/Src/IronPython.SQLite/Row.cs
index 75215ced7..baef4eb67 100644
--- a/Src/IronPython.SQLite/Row.cs
+++ b/Src/IronPython.SQLite/Row.cs
@@ -6,65 +6,52 @@
//
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using IronPython.Runtime;
using System.Collections;
+
+using IronPython.Runtime;
using IronPython.Runtime.Exceptions;
-namespace IronPython.SQLite
-{
- public static partial class PythonSQLite
- {
+namespace IronPython.SQLite {
+ public static partial class PythonSQLite {
[PythonType]
- public class Row : IEnumerable
- {
+ public class Row : IEnumerable {
private PythonTuple data;
private PythonTuple description;
- public Row(Cursor cursor, PythonTuple data)
- {
+ public Row(Cursor cursor, PythonTuple data) {
this.data = data;
this.description = cursor.description;
}
- public override bool Equals(object obj)
- {
+ public override bool Equals(object obj) {
Row other = obj as Row;
- if(other == null)
+ if (other == null)
return false;
- if(object.ReferenceEquals(this, other))
+ if (object.ReferenceEquals(this, other))
return true;
return this.description.Equals(other.description) && this.data.Equals(other.data);
}
- public override int GetHashCode()
- {
+ public override int GetHashCode() {
return description.GetHashCode() ^ data.GetHashCode();
}
- public object __iter__()
- {
+ public object __iter__() {
return data;
}
- public object this[long i]
- {
+ public object this[long i] {
get { return this.data[i]; }
}
- public object this[string s]
- {
- get
- {
- for(int i = 0; i < data.Count; ++i)
- {
+ public object this[string s] {
+ get {
+ for (int i = 0; i < data.Count; ++i) {
PythonTuple col_desc = (PythonTuple)description[i];
- if(s.Equals((string)col_desc[0], StringComparison.OrdinalIgnoreCase))
+ if (s.Equals((string)col_desc[0], StringComparison.OrdinalIgnoreCase))
return data[i];
}
@@ -72,12 +59,10 @@ public object this[string s]
}
}
- public PythonList keys()
- {
+ public PythonList keys() {
PythonList list = new PythonList();
- for(int i = 0; i < data.Count; ++i)
- {
+ for (int i = 0; i < data.Count; ++i) {
list.append(((PythonTuple)description[i])[0]);
}
@@ -86,8 +71,7 @@ public PythonList keys()
#region IEnumerable Members
- public IEnumerator GetEnumerator()
- {
+ public IEnumerator GetEnumerator() {
return data.GetEnumerator();
}
diff --git a/Src/IronPython.SQLite/Statement.cs b/Src/IronPython.SQLite/Statement.cs
index 373787b47..8eb121ec6 100644
--- a/Src/IronPython.SQLite/Statement.cs
+++ b/Src/IronPython.SQLite/Statement.cs
@@ -8,17 +8,17 @@
using System;
using System.Collections;
using System.Diagnostics;
+
using Community.CsharpSqlite;
+
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
using sqlite3_stmt = Community.CsharpSqlite.Sqlite3.Vdbe;
-namespace IronPython.SQLite
-{
- internal enum StatementType
- {
+namespace IronPython.SQLite {
+ internal enum StatementType {
Unknown,
Select,
Insert,
@@ -29,8 +29,7 @@ internal enum StatementType
}
[DebuggerDisplay("{sql}")]
- internal class Statement
- {
+ internal class Statement {
private readonly Guid uniqueid;
private Sqlite3.sqlite3 db;
internal sqlite3_stmt st;
@@ -43,8 +42,7 @@ internal class Statement
public string Tail { get; private set; }
- public Statement(PythonSQLite.Connection connection, string operation)
- {
+ public Statement(PythonSQLite.Connection connection, string operation) {
this.uniqueid = Guid.NewGuid();
this.db = connection.db;
@@ -52,8 +50,7 @@ public Statement(PythonSQLite.Connection connection, string operation)
this.st = null;
string tail = null;
- if(Sqlite3.sqlite3_prepare(this.db, this.sql, -1, ref this.st, ref tail) != Sqlite3.SQLITE_OK /*TODO: || too much sql */)
- {
+ if (Sqlite3.sqlite3_prepare(this.db, this.sql, -1, ref this.st, ref tail) != Sqlite3.SQLITE_OK /*TODO: || too much sql */) {
Sqlite3.sqlite3_finalize(st);
this.st = null;
throw PythonSQLite.GetSqliteError(this.db, null);
@@ -62,8 +59,7 @@ public Statement(PythonSQLite.Connection connection, string operation)
this.Tail = tail;
}
- private Statement(Sqlite3.sqlite3 db, sqlite3_stmt stmt, string operation, string tail)
- {
+ private Statement(Sqlite3.sqlite3 db, sqlite3_stmt stmt, string operation, string tail) {
this.uniqueid = Guid.NewGuid();
this.db = db;
@@ -73,10 +69,8 @@ private Statement(Sqlite3.sqlite3 db, sqlite3_stmt stmt, string operation, strin
this.Tail = tail;
}
- ~Statement()
- {
- if(this.st != null)
- {
+ ~Statement() {
+ if (this.st != null) {
Sqlite3.sqlite3_finalize(this.st);
}
@@ -84,24 +78,22 @@ private Statement(Sqlite3.sqlite3 db, sqlite3_stmt stmt, string operation, strin
}
private StatementType _type = StatementType.Unknown;
- public StatementType StatementType
- {
- get
- {
- if(this._type != StatementType.Unknown)
+ public StatementType StatementType {
+ get {
+ if (this._type != StatementType.Unknown)
return _type;
string s = this.sql.TrimStart();
- if(s.StartsWith("select", StringComparison.InvariantCultureIgnoreCase))
+ if (s.StartsWith("select", StringComparison.InvariantCultureIgnoreCase))
this._type = StatementType.Select;
- else if(s.StartsWith("insert", StringComparison.InvariantCultureIgnoreCase))
+ else if (s.StartsWith("insert", StringComparison.InvariantCultureIgnoreCase))
this._type = StatementType.Insert;
- else if(s.StartsWith("update", StringComparison.InvariantCultureIgnoreCase))
+ else if (s.StartsWith("update", StringComparison.InvariantCultureIgnoreCase))
this._type = StatementType.Update;
- else if(s.StartsWith("delete", StringComparison.InvariantCultureIgnoreCase))
+ else if (s.StartsWith("delete", StringComparison.InvariantCultureIgnoreCase))
this._type = StatementType.Delete;
- else if(s.StartsWith("replace", StringComparison.InvariantCultureIgnoreCase))
+ else if (s.StartsWith("replace", StringComparison.InvariantCultureIgnoreCase))
this._type = StatementType.Replace;
else
this._type = StatementType.Other;
@@ -110,24 +102,22 @@ public StatementType StatementType
}
}
- public void BindParameters(CodeContext context, object parameters)
- {
- if(bound)
+ public void BindParameters(CodeContext context, object parameters) {
+ if (bound)
this.ClearParameters();
int num_params_needed = Sqlite3.sqlite3_bind_parameter_count(this.st);
- if(parameters == null)
- {
- if(num_params_needed > 0)
+ if (parameters == null) {
+ if (num_params_needed > 0)
throw PythonSQLite.MakeProgrammingError("parameters are required but not specified.");
else
return;
}
- if(parameters is IDictionary)
+ if (parameters is IDictionary)
BindParameters(context, (IDictionary)parameters, num_params_needed);
- else if(parameters is IList)
+ else if (parameters is IList)
BindParameters(context, (IList)parameters, num_params_needed);
else
throw PythonSQLite.MakeProgrammingError("unknown parameter type");
@@ -135,72 +125,65 @@ public void BindParameters(CodeContext context, object parameters)
bound = true;
}
- private void BindParameters(CodeContext context, IDictionary args, int num_params_needed)
- {
- for(int i = 1; i <= num_params_needed; ++i)
- {
+ private void BindParameters(CodeContext context, IDictionary args, int num_params_needed) {
+ for (int i = 1; i <= num_params_needed; ++i) {
string binding_name = Sqlite3.sqlite3_bind_parameter_name(this.st, i);
- if(string.IsNullOrEmpty(binding_name))
+ if (string.IsNullOrEmpty(binding_name))
throw PythonSQLite.MakeProgrammingError("Binding {0} has no name, but you supplied a dictionary (which has only names).".Format(i));
// remove the leading colon
binding_name = binding_name.Substring(1);
- if(args.Contains(binding_name))
+ if (args.Contains(binding_name))
BindParameter(context, i, maybeAdapt(context, args[binding_name]));
else
throw PythonSQLite.MakeProgrammingError("You did not supply a value for binding {0}.".Format(i));
}
}
- private void BindParameters(CodeContext context, IList args, int num_params_needed)
- {
- if(num_params_needed != args.Count)
+ private void BindParameters(CodeContext context, IList args, int num_params_needed) {
+ if (num_params_needed != args.Count)
throw PythonSQLite.MakeProgrammingError("Incorrect number of bindings supplied.");
- for(int i = 0; i < args.Count; ++i)
- {
+ for (int i = 0; i < args.Count; ++i) {
BindParameter(context, i + 1, maybeAdapt(context, args[i]));
}
}
- private void BindParameter(CodeContext context, int index, object arg)
- {
+ private void BindParameter(CodeContext context, int index, object arg) {
int rc;
- if(arg == null)
+ if (arg == null)
rc = Sqlite3.sqlite3_bind_null(st, index);
- else if(arg is int)
+ else if (arg is int)
rc = Sqlite3.sqlite3_bind_int(st, index, (int)arg);
- else if(arg is bool)
+ else if (arg is bool)
rc = Sqlite3.sqlite3_bind_int(st, index, (bool)arg ? 1 : 0);
- else if(arg is long)
+ else if (arg is long)
rc = Sqlite3.sqlite3_bind_int64(st, index, (long)arg);
else if (arg is System.Numerics.BigInteger)
rc = Sqlite3.sqlite3_bind_int64(st, index, (long)((System.Numerics.BigInteger)arg));
- else if(arg is float)
+ else if (arg is float)
rc = Sqlite3.sqlite3_bind_double(st, index, (float)arg);
- else if(arg is double)
+ else if (arg is double)
rc = Sqlite3.sqlite3_bind_double(st, index, (double)arg);
- else if(arg is string)
+ else if (arg is string)
rc = Sqlite3.sqlite3_bind_text(st, index, (string)arg, -1, Sqlite3.SQLITE_TRANSIENT);
- else if(arg is byte[])
+ else if (arg is byte[])
rc = Sqlite3.sqlite3_bind_blob(this.st, index, (byte[])arg, -1, Sqlite3.SQLITE_TRANSIENT);
else
throw PythonSQLite.MakeInterfaceError("Unable to bind parameter {0} - unsupported type {1}".Format(index, arg.GetType()));
- if(rc != Sqlite3.SQLITE_OK)
+ if (rc != Sqlite3.SQLITE_OK)
throw PythonSQLite.MakeInterfaceError("Unable to bind parameter {0}: {1}".Format(index, Sqlite3.sqlite3_errmsg(db)));
}
- private object maybeAdapt(CodeContext context, object value)
- {
+ private object maybeAdapt(CodeContext context, object value) {
return needsAdaptation(context, value) ? adaptValue(context, value) : value;
}
- private bool needsAdaptation(CodeContext context, object value)
- {
+ private bool needsAdaptation(CodeContext context, object value) {
// TODO The check for primitive types could probably be cached like pysqlite does
- if(value == null ||
+ if (value == null ||
value is int ||
value is bool ||
value is long ||
@@ -208,31 +191,26 @@ value is System.Numerics.BigInteger ||
value is float ||
value is double ||
value is string ||
- value is byte[])
- {
+ value is byte[]) {
object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol));
object type = DynamicHelpers.GetPythonType(value);
object key = new PythonTuple(new[] { type, proto });
return PythonSQLite.adapters.ContainsKey(key);
- }
- else
- {
+ } else {
return true;
}
}
- private object adaptValue(CodeContext context, object value)
- {
+ private object adaptValue(CodeContext context, object value) {
object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PythonSQLite.PrepareProtocol));
object type = DynamicHelpers.GetPythonType(value);
object key = new PythonTuple(new[] { type, proto });
object adapter;
- if(PythonSQLite.adapters.TryGetValue(key, out adapter))
- {
+ if (PythonSQLite.adapters.TryGetValue(key, out adapter)) {
object adapted = PythonCalls.Call(context, adapter, value);
return adapted;
}
@@ -240,11 +218,9 @@ private object adaptValue(CodeContext context, object value)
// TODO: Use proto? Any value whatsoever?
object conform;
- if(context.LanguageContext.Operations.TryGetMember(value, "__conform__", out conform))
- {
+ if (context.LanguageContext.Operations.TryGetMember(value, "__conform__", out conform)) {
object adapted = PythonCalls.Call(context, conform, proto);
- if(adapted != null)
- {
+ if (adapted != null) {
return adapted;
}
}
@@ -252,17 +228,14 @@ private object adaptValue(CodeContext context, object value)
return value;
}
- public int RawStep()
- {
+ public int RawStep() {
return Util.Step(st);
}
- public int SqliteFinalize()
- {
+ public int SqliteFinalize() {
int rc = Sqlite3.SQLITE_OK;
- if(this.st != null)
- {
+ if (this.st != null) {
rc = Sqlite3.sqlite3_finalize(this.st);
this.st = null;
}
@@ -272,40 +245,34 @@ public int SqliteFinalize()
return rc;
}
- public int Reset()
- {
+ public int Reset() {
int rc = Sqlite3.SQLITE_OK;
- if(this.in_use && this.st != null)
- {
+ if (this.in_use && this.st != null) {
rc = Sqlite3.sqlite3_reset(this.st);
- if(rc == Sqlite3.SQLITE_OK)
+ if (rc == Sqlite3.SQLITE_OK)
this.in_use = false;
}
return rc;
}
- private void ClearParameters()
- {
- if(Sqlite3.sqlite3_clear_bindings(this.st) != Sqlite3.SQLITE_OK)
+ private void ClearParameters() {
+ if (Sqlite3.sqlite3_clear_bindings(this.st) != Sqlite3.SQLITE_OK)
throw PythonSQLite.GetSqliteError(this.db, null);
}
- internal void MarkDirty()
- {
+ internal void MarkDirty() {
this.in_use = true;
}
- internal int Recompile(CodeContext context, object parameters)
- {
+ internal int Recompile(CodeContext context, object parameters) {
sqlite3_stmt new_st = null;
string tail = null;
int rc = Sqlite3.sqlite3_prepare(this.db, this.sql, -1, ref new_st, ref tail);
- if(rc == Sqlite3.SQLITE_OK)
- {
+ if (rc == Sqlite3.SQLITE_OK) {
Statement new_stmt = new Statement(this.st.db, new_st, this.sql, tail);
new_stmt.BindParameters(context, parameters);
diff --git a/Src/IronPython.SQLite/Util.cs b/Src/IronPython.SQLite/Util.cs
index ab23d0b28..d0a370c5d 100644
--- a/Src/IronPython.SQLite/Util.cs
+++ b/Src/IronPython.SQLite/Util.cs
@@ -7,13 +7,10 @@
using Community.CsharpSqlite;
-namespace IronPython.SQLite
-{
- internal static class Util
- {
- public static int Step(Sqlite3.Vdbe statement)
- {
- if(statement == null)
+namespace IronPython.SQLite {
+ internal static class Util {
+ public static int Step(Sqlite3.Vdbe statement) {
+ if (statement == null)
return Sqlite3.SQLITE_OK;
else
return Sqlite3.sqlite3_step(statement);
diff --git a/Src/IronPython.SQLite/_sqlite.cs b/Src/IronPython.SQLite/_sqlite.cs
index 732a93db3..9d62d6b28 100644
--- a/Src/IronPython.SQLite/_sqlite.cs
+++ b/Src/IronPython.SQLite/_sqlite.cs
@@ -7,21 +7,20 @@
using System;
using System.Runtime.CompilerServices;
-using System.Runtime.InteropServices;
using System.Text;
+
using Community.CsharpSqlite;
+
using IronPython.Runtime;
using IronPython.Runtime.Operations;
using IronPython.Runtime.Types;
+
using Microsoft.Scripting.Runtime;
-using Microsoft.Scripting.Utils;
[assembly: PythonModule("_sqlite3", typeof(IronPython.SQLite.PythonSQLite))]
-namespace IronPython.SQLite
-{
- public static partial class PythonSQLite
- {
+namespace IronPython.SQLite {
+ public static partial class PythonSQLite {
public static readonly string version = typeof(PythonSQLite).Assembly.GetName().Version.ToString(3);
public static readonly string sqlite_version = Sqlite3.sqlite3_version.Replace("(C#)", "");
@@ -33,21 +32,19 @@ public static partial class PythonSQLite
internal static Encoding Latin1 = Encoding.GetEncoding("iso-8859-1");
[SpecialName]
- public static void PerformModuleReload(PythonContext context, PythonDictionary dict)
- {
+ public static void PerformModuleReload(PythonContext context, PythonDictionary dict) {
InitModuleExceptions(context, dict);
}
public static object connect(CodeContext context,
string database,
- double timeout=0.0,
- int detect_types=0,
- string isolation_level=null,
- bool check_same_thread=true,
- object factory=null,
- int cached_statements=0)
- {
- if(factory == null)
+ double timeout = 0.0,
+ int detect_types = 0,
+ string isolation_level = null,
+ bool check_same_thread = true,
+ object factory = null,
+ int cached_statements = 0) {
+ if (factory == null)
return new Connection(database, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements);
else
return PythonCalls.Call(context, factory, database, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements);
@@ -56,8 +53,7 @@ public static object connect(CodeContext context,
[Documentation(@"register_adapter(type, callable)
Registers an adapter with pysqlite's adapter registry. Non-standard.")]
- public static void register_adapter(CodeContext context, PythonType type, object adapter)
- {
+ public static void register_adapter(CodeContext context, PythonType type, object adapter) {
object proto = DynamicHelpers.GetPythonTypeFromType(typeof(PrepareProtocol));
object key = new PythonTuple(new object[] { type, proto });
adapters[key] = adapter;
@@ -66,8 +62,7 @@ public static void register_adapter(CodeContext context, PythonType type, object
[Documentation(@"register_converter(typename, callable)
Registers a converter with pysqlite. Non-standard.")]
- public static void register_converter(CodeContext context, string type, object converter)
- {
+ public static void register_converter(CodeContext context, string type, object converter) {
converters[type.ToUpperInvariant()] = converter;
}
diff --git a/Src/IronPython.SQLite/c#sqlite/BtreeInt_h.cs b/Src/IronPython.SQLite/c#sqlite/BtreeInt_h.cs
index e68d86db3..064daab41 100644
--- a/Src/IronPython.SQLite/c#sqlite/BtreeInt_h.cs
+++ b/Src/IronPython.SQLite/c#sqlite/BtreeInt_h.cs
@@ -3,515 +3,499 @@
using i16 = System.Int16;
using i64 = System.Int64;
-using u8 = System.Byte;
+using Pgno = System.UInt32;
+using sqlite3_int64 = System.Int64;
using u16 = System.UInt16;
using u32 = System.UInt32;
-using u64 = System.UInt64;
-
-using sqlite3_int64 = System.Int64;
-using Pgno = System.UInt32;
-
-namespace Community.CsharpSqlite
-{
- using DbPage = Sqlite3.PgHdr;
-
- public partial class Sqlite3
- {
- /*
- ** 2004 April 6
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- **
- ** This file implements a external (disk-based) database using BTrees.
- ** For a detailed discussion of BTrees, refer to
- **
- ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
- ** "Sorting And Searching", pages 473-480. Addison-Wesley
- ** Publishing Company, Reading, Massachusetts.
- **
- ** The basic idea is that each page of the file contains N database
- ** entries and N+1 pointers to subpages.
- **
- ** ----------------------------------------------------------------
- ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
- ** ----------------------------------------------------------------
- **
- ** All of the keys on the page that Ptr(0) points to have values less
- ** than Key(0). All of the keys on page Ptr(1) and its subpages have
- ** values greater than Key(0) and less than Key(1). All of the keys
- ** on Ptr(N) and its subpages have values greater than Key(N-1). And
- ** so forth.
- **
- ** Finding a particular key requires reading O(log(M)) pages from the
- ** disk where M is the number of entries in the tree.
- **
- ** In this implementation, a single file can hold one or more separate
- ** BTrees. Each BTree is identified by the index of its root page. The
- ** key and data for any entry are combined to form the "payload". A
- ** fixed amount of payload can be carried directly on the database
- ** page. If the payload is larger than the preset amount then surplus
- ** bytes are stored on overflow pages. The payload for an entry
- ** and the preceding pointer are combined to form a "Cell". Each
- ** page has a small header which contains the Ptr(N) pointer and other
- ** information such as the size of key and data.
- **
- ** FORMAT DETAILS
- **
- ** The file is divided into pages. The first page is called page 1,
- ** the second is page 2, and so forth. A page number of zero indicates
- ** "no such page". The page size can be any power of 2 between 512 and 65536.
- ** Each page can be either a btree page, a freelist page, an overflow
- ** page, or a pointer-map page.
- **
- ** The first page is always a btree page. The first 100 bytes of the first
- ** page contain a special header (the "file header") that describes the file.
- ** The format of the file header is as follows:
- **
- ** OFFSET SIZE DESCRIPTION
- ** 0 16 Header string: "SQLite format 3\000"
- ** 16 2 Page size in bytes.
- ** 18 1 File format write version
- ** 19 1 File format read version
- ** 20 1 Bytes of unused space at the end of each page
- ** 21 1 Max embedded payload fraction
- ** 22 1 Min embedded payload fraction
- ** 23 1 Min leaf payload fraction
- ** 24 4 File change counter
- ** 28 4 Reserved for future use
- ** 32 4 First freelist page
- ** 36 4 Number of freelist pages in the file
- ** 40 60 15 4-byte meta values passed to higher layers
- **
- ** 40 4 Schema cookie
- ** 44 4 File format of schema layer
- ** 48 4 Size of page cache
- ** 52 4 Largest root-page (auto/incr_vacuum)
- ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
- ** 60 4 User version
- ** 64 4 Incremental vacuum mode
- ** 68 4 unused
- ** 72 4 unused
- ** 76 4 unused
- **
- ** All of the integer values are big-endian (most significant byte first).
- **
- ** The file change counter is incremented when the database is changed
- ** This counter allows other processes to know when the file has changed
- ** and thus when they need to flush their cache.
- **
- ** The max embedded payload fraction is the amount of the total usable
- ** space in a page that can be consumed by a single cell for standard
- ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
- ** is to limit the maximum cell size so that at least 4 cells will fit
- ** on one page. Thus the default max embedded payload fraction is 64.
- **
- ** If the payload for a cell is larger than the max payload, then extra
- ** payload is spilled to overflow pages. Once an overflow page is allocated,
- ** as many bytes as possible are moved into the overflow pages without letting
- ** the cell size drop below the min embedded payload fraction.
- **
- ** The min leaf payload fraction is like the min embedded payload fraction
- ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
- ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
- ** not specified in the header.
- **
- ** Each btree pages is divided into three sections: The header, the
- ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
- ** file header that occurs before the page header.
- **
- ** |----------------|
- ** | file header | 100 bytes. Page 1 only.
- ** |----------------|
- ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
- ** |----------------|
- ** | cell pointer | | 2 bytes per cell. Sorted order.
- ** | array | | Grows downward
- ** | | v
- ** |----------------|
- ** | unallocated |
- ** | space |
- ** |----------------| ^ Grows upwards
- ** | cell content | | Arbitrary order interspersed with freeblocks.
- ** | area | | and free space fragments.
- ** |----------------|
- **
- ** The page headers looks like this:
- **
- ** OFFSET SIZE DESCRIPTION
- ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
- ** 1 2 byte offset to the first freeblock
- ** 3 2 number of cells on this page
- ** 5 2 first byte of the cell content area
- ** 7 1 number of fragmented free bytes
- ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
- **
- ** The flags define the format of this btree page. The leaf flag means that
- ** this page has no children. The zerodata flag means that this page carries
- ** only keys and no data. The intkey flag means that the key is a integer
- ** which is stored in the key size entry of the cell header rather than in
- ** the payload area.
- **
- ** The cell pointer array begins on the first byte after the page header.
- ** The cell pointer array contains zero or more 2-byte numbers which are
- ** offsets from the beginning of the page to the cell content in the cell
- ** content area. The cell pointers occur in sorted order. The system strives
- ** to keep free space after the last cell pointer so that new cells can
- ** be easily added without having to defragment the page.
- **
- ** Cell content is stored at the very end of the page and grows toward the
- ** beginning of the page.
- **
- ** Unused space within the cell content area is collected into a linked list of
- ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
- ** to the first freeblock is given in the header. Freeblocks occur in
- ** increasing order. Because a freeblock must be at least 4 bytes in size,
- ** any group of 3 or fewer unused bytes in the cell content area cannot
- ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
- ** a fragment. The total number of bytes in all fragments is recorded.
- ** in the page header at offset 7.
- **
- ** SIZE DESCRIPTION
- ** 2 Byte offset of the next freeblock
- ** 2 Bytes in this freeblock
- **
- ** Cells are of variable length. Cells are stored in the cell content area at
- ** the end of the page. Pointers to the cells are in the cell pointer array
- ** that immediately follows the page header. Cells is not necessarily
- ** contiguous or in order, but cell pointers are contiguous and in order.
- **
- ** Cell content makes use of variable length integers. A variable
- ** length integer is 1 to 9 bytes where the lower 7 bits of each
- ** byte are used. The integer consists of all bytes that have bit 8 set and
- ** the first byte with bit 8 clear. The most significant byte of the integer
- ** appears first. A variable-length integer may not be more than 9 bytes long.
- ** As a special case, all 8 bytes of the 9th byte are used as data. This
- ** allows a 64-bit integer to be encoded in 9 bytes.
- **
- ** 0x00 becomes 0x00000000
- ** 0x7f becomes 0x0000007f
- ** 0x81 0x00 becomes 0x00000080
- ** 0x82 0x00 becomes 0x00000100
- ** 0x80 0x7f becomes 0x0000007f
- ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
- ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
- **
- ** Variable length integers are used for rowids and to hold the number of
- ** bytes of key and data in a btree cell.
- **
- ** The content of a cell looks like this:
- **
- ** SIZE DESCRIPTION
- ** 4 Page number of the left child. Omitted if leaf flag is set.
- ** var Number of bytes of data. Omitted if the zerodata flag is set.
- ** var Number of bytes of key. Or the key itself if intkey flag is set.
- ** * Payload
- ** 4 First page of the overflow chain. Omitted if no overflow
- **
- ** Overflow pages form a linked list. Each page except the last is completely
- ** filled with data (pagesize - 4 bytes). The last page can have as little
- ** as 1 byte of data.
- **
- ** SIZE DESCRIPTION
- ** 4 Page number of next overflow page
- ** * Data
- **
- ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
- ** file header points to the first in a linked list of trunk page. Each trunk
- ** page points to multiple leaf pages. The content of a leaf page is
- ** unspecified. A trunk page looks like this:
- **
- ** SIZE DESCRIPTION
- ** 4 Page number of next trunk page
- ** 4 Number of leaf pointers on this page
- ** * zero or more pages numbers of leaves
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
+using u8 = System.Byte;
- /* The following value is the maximum cell size assuming a maximum page
- ** size give above.
- */
- //#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
- static int MX_CELL_SIZE( BtShared pBt )
- {
- return (int)( pBt.pageSize - 8 );
- }
+namespace Community.CsharpSqlite {
+ using DbPage = Sqlite3.PgHdr;
+
+ public partial class Sqlite3 {
+ /*
+ ** 2004 April 6
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ **
+ ** This file implements a external (disk-based) database using BTrees.
+ ** For a detailed discussion of BTrees, refer to
+ **
+ ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
+ ** "Sorting And Searching", pages 473-480. Addison-Wesley
+ ** Publishing Company, Reading, Massachusetts.
+ **
+ ** The basic idea is that each page of the file contains N database
+ ** entries and N+1 pointers to subpages.
+ **
+ ** ----------------------------------------------------------------
+ ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
+ ** ----------------------------------------------------------------
+ **
+ ** All of the keys on the page that Ptr(0) points to have values less
+ ** than Key(0). All of the keys on page Ptr(1) and its subpages have
+ ** values greater than Key(0) and less than Key(1). All of the keys
+ ** on Ptr(N) and its subpages have values greater than Key(N-1). And
+ ** so forth.
+ **
+ ** Finding a particular key requires reading O(log(M)) pages from the
+ ** disk where M is the number of entries in the tree.
+ **
+ ** In this implementation, a single file can hold one or more separate
+ ** BTrees. Each BTree is identified by the index of its root page. The
+ ** key and data for any entry are combined to form the "payload". A
+ ** fixed amount of payload can be carried directly on the database
+ ** page. If the payload is larger than the preset amount then surplus
+ ** bytes are stored on overflow pages. The payload for an entry
+ ** and the preceding pointer are combined to form a "Cell". Each
+ ** page has a small header which contains the Ptr(N) pointer and other
+ ** information such as the size of key and data.
+ **
+ ** FORMAT DETAILS
+ **
+ ** The file is divided into pages. The first page is called page 1,
+ ** the second is page 2, and so forth. A page number of zero indicates
+ ** "no such page". The page size can be any power of 2 between 512 and 65536.
+ ** Each page can be either a btree page, a freelist page, an overflow
+ ** page, or a pointer-map page.
+ **
+ ** The first page is always a btree page. The first 100 bytes of the first
+ ** page contain a special header (the "file header") that describes the file.
+ ** The format of the file header is as follows:
+ **
+ ** OFFSET SIZE DESCRIPTION
+ ** 0 16 Header string: "SQLite format 3\000"
+ ** 16 2 Page size in bytes.
+ ** 18 1 File format write version
+ ** 19 1 File format read version
+ ** 20 1 Bytes of unused space at the end of each page
+ ** 21 1 Max embedded payload fraction
+ ** 22 1 Min embedded payload fraction
+ ** 23 1 Min leaf payload fraction
+ ** 24 4 File change counter
+ ** 28 4 Reserved for future use
+ ** 32 4 First freelist page
+ ** 36 4 Number of freelist pages in the file
+ ** 40 60 15 4-byte meta values passed to higher layers
+ **
+ ** 40 4 Schema cookie
+ ** 44 4 File format of schema layer
+ ** 48 4 Size of page cache
+ ** 52 4 Largest root-page (auto/incr_vacuum)
+ ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
+ ** 60 4 User version
+ ** 64 4 Incremental vacuum mode
+ ** 68 4 unused
+ ** 72 4 unused
+ ** 76 4 unused
+ **
+ ** All of the integer values are big-endian (most significant byte first).
+ **
+ ** The file change counter is incremented when the database is changed
+ ** This counter allows other processes to know when the file has changed
+ ** and thus when they need to flush their cache.
+ **
+ ** The max embedded payload fraction is the amount of the total usable
+ ** space in a page that can be consumed by a single cell for standard
+ ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
+ ** is to limit the maximum cell size so that at least 4 cells will fit
+ ** on one page. Thus the default max embedded payload fraction is 64.
+ **
+ ** If the payload for a cell is larger than the max payload, then extra
+ ** payload is spilled to overflow pages. Once an overflow page is allocated,
+ ** as many bytes as possible are moved into the overflow pages without letting
+ ** the cell size drop below the min embedded payload fraction.
+ **
+ ** The min leaf payload fraction is like the min embedded payload fraction
+ ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
+ ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
+ ** not specified in the header.
+ **
+ ** Each btree pages is divided into three sections: The header, the
+ ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
+ ** file header that occurs before the page header.
+ **
+ ** |----------------|
+ ** | file header | 100 bytes. Page 1 only.
+ ** |----------------|
+ ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
+ ** |----------------|
+ ** | cell pointer | | 2 bytes per cell. Sorted order.
+ ** | array | | Grows downward
+ ** | | v
+ ** |----------------|
+ ** | unallocated |
+ ** | space |
+ ** |----------------| ^ Grows upwards
+ ** | cell content | | Arbitrary order interspersed with freeblocks.
+ ** | area | | and free space fragments.
+ ** |----------------|
+ **
+ ** The page headers looks like this:
+ **
+ ** OFFSET SIZE DESCRIPTION
+ ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
+ ** 1 2 byte offset to the first freeblock
+ ** 3 2 number of cells on this page
+ ** 5 2 first byte of the cell content area
+ ** 7 1 number of fragmented free bytes
+ ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
+ **
+ ** The flags define the format of this btree page. The leaf flag means that
+ ** this page has no children. The zerodata flag means that this page carries
+ ** only keys and no data. The intkey flag means that the key is a integer
+ ** which is stored in the key size entry of the cell header rather than in
+ ** the payload area.
+ **
+ ** The cell pointer array begins on the first byte after the page header.
+ ** The cell pointer array contains zero or more 2-byte numbers which are
+ ** offsets from the beginning of the page to the cell content in the cell
+ ** content area. The cell pointers occur in sorted order. The system strives
+ ** to keep free space after the last cell pointer so that new cells can
+ ** be easily added without having to defragment the page.
+ **
+ ** Cell content is stored at the very end of the page and grows toward the
+ ** beginning of the page.
+ **
+ ** Unused space within the cell content area is collected into a linked list of
+ ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
+ ** to the first freeblock is given in the header. Freeblocks occur in
+ ** increasing order. Because a freeblock must be at least 4 bytes in size,
+ ** any group of 3 or fewer unused bytes in the cell content area cannot
+ ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
+ ** a fragment. The total number of bytes in all fragments is recorded.
+ ** in the page header at offset 7.
+ **
+ ** SIZE DESCRIPTION
+ ** 2 Byte offset of the next freeblock
+ ** 2 Bytes in this freeblock
+ **
+ ** Cells are of variable length. Cells are stored in the cell content area at
+ ** the end of the page. Pointers to the cells are in the cell pointer array
+ ** that immediately follows the page header. Cells is not necessarily
+ ** contiguous or in order, but cell pointers are contiguous and in order.
+ **
+ ** Cell content makes use of variable length integers. A variable
+ ** length integer is 1 to 9 bytes where the lower 7 bits of each
+ ** byte are used. The integer consists of all bytes that have bit 8 set and
+ ** the first byte with bit 8 clear. The most significant byte of the integer
+ ** appears first. A variable-length integer may not be more than 9 bytes long.
+ ** As a special case, all 8 bytes of the 9th byte are used as data. This
+ ** allows a 64-bit integer to be encoded in 9 bytes.
+ **
+ ** 0x00 becomes 0x00000000
+ ** 0x7f becomes 0x0000007f
+ ** 0x81 0x00 becomes 0x00000080
+ ** 0x82 0x00 becomes 0x00000100
+ ** 0x80 0x7f becomes 0x0000007f
+ ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
+ ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
+ **
+ ** Variable length integers are used for rowids and to hold the number of
+ ** bytes of key and data in a btree cell.
+ **
+ ** The content of a cell looks like this:
+ **
+ ** SIZE DESCRIPTION
+ ** 4 Page number of the left child. Omitted if leaf flag is set.
+ ** var Number of bytes of data. Omitted if the zerodata flag is set.
+ ** var Number of bytes of key. Or the key itself if intkey flag is set.
+ ** * Payload
+ ** 4 First page of the overflow chain. Omitted if no overflow
+ **
+ ** Overflow pages form a linked list. Each page except the last is completely
+ ** filled with data (pagesize - 4 bytes). The last page can have as little
+ ** as 1 byte of data.
+ **
+ ** SIZE DESCRIPTION
+ ** 4 Page number of next overflow page
+ ** * Data
+ **
+ ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
+ ** file header points to the first in a linked list of trunk page. Each trunk
+ ** page points to multiple leaf pages. The content of a leaf page is
+ ** unspecified. A trunk page looks like this:
+ **
+ ** SIZE DESCRIPTION
+ ** 4 Page number of next trunk page
+ ** 4 Number of leaf pointers on this page
+ ** * zero or more pages numbers of leaves
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
+
+ /* The following value is the maximum cell size assuming a maximum page
+ ** size give above.
+ */
+ //#define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
+ static int MX_CELL_SIZE(BtShared pBt) {
+ return (int)(pBt.pageSize - 8);
+ }
- /* The maximum number of cells on a single page of the database. This
- ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
- ** plus 2 bytes for the index to the cell in the page header). Such
- ** small cells will be rare, but they are possible.
- */
- //#define MX_CELL(pBt) ((pBt.pageSize-8)/6)
- static int MX_CELL( BtShared pBt )
- {
- return ( (int)( pBt.pageSize - 8 ) / 6 );
- }
+ /* The maximum number of cells on a single page of the database. This
+ ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
+ ** plus 2 bytes for the index to the cell in the page header). Such
+ ** small cells will be rare, but they are possible.
+ */
+ //#define MX_CELL(pBt) ((pBt.pageSize-8)/6)
+ static int MX_CELL(BtShared pBt) {
+ return ((int)(pBt.pageSize - 8) / 6);
+ }
- /* Forward declarations */
- //typedef struct MemPage MemPage;
- //typedef struct BtLock BtLock;
-
- /*
- ** This is a magic string that appears at the beginning of every
- ** SQLite database in order to identify the file as a real database.
- **
- ** You can change this value at compile-time by specifying a
- ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
- ** header must be exactly 16 bytes including the zero-terminator so
- ** the string itself should be 15 characters long. If you change
- ** the header, then your custom library will not be able to read
- ** databases generated by the standard tools and the standard tools
- ** will not be able to read databases created by your custom library.
- */
+ /* Forward declarations */
+ //typedef struct MemPage MemPage;
+ //typedef struct BtLock BtLock;
+
+ /*
+ ** This is a magic string that appears at the beginning of every
+ ** SQLite database in order to identify the file as a real database.
+ **
+ ** You can change this value at compile-time by specifying a
+ ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
+ ** header must be exactly 16 bytes including the zero-terminator so
+ ** the string itself should be 15 characters long. If you change
+ ** the header, then your custom library will not be able to read
+ ** databases generated by the standard tools and the standard tools
+ ** will not be able to read databases created by your custom library.
+ */
#if !SQLITE_FILE_HEADER //* 123456789 123456 */
- const string SQLITE_FILE_HEADER = "SQLite format 3\0";
+ const string SQLITE_FILE_HEADER = "SQLite format 3\0";
#endif
- /*
-** Page type flags. An ORed combination of these flags appear as the
-** first byte of on-disk image of every BTree page.
-*/
- const byte PTF_INTKEY = 0x01;
- const byte PTF_ZERODATA = 0x02;
- const byte PTF_LEAFDATA = 0x04;
- const byte PTF_LEAF = 0x08;
-
- /*
- ** As each page of the file is loaded into memory, an instance of the following
- ** structure is appended and initialized to zero. This structure stores
- ** information about the page that is decoded from the raw file page.
- **
- ** The pParent field points back to the parent page. This allows us to
- ** walk up the BTree from any leaf to the root. Care must be taken to
- ** unref() the parent page pointer when this page is no longer referenced.
- ** The pageDestructor() routine handles that chore.
- **
- ** Access to all fields of this structure is controlled by the mutex
- ** stored in MemPage.pBt.mutex.
- */
- public struct _OvflCell
- { /* Cells that will not fit on aData[] */
- public u8[] pCell; /* Pointers to the body of the overflow cell */
- public u16 idx; /* Insert this cell before idx-th non-overflow cell */
- public _OvflCell Copy()
- {
- _OvflCell cp = new _OvflCell();
- if ( pCell != null )
- {
- cp.pCell = sqlite3Malloc( pCell.Length );
- Buffer.BlockCopy( pCell, 0, cp.pCell, 0, pCell.Length );
- }
- cp.idx = idx;
- return cp;
- }
- };
- public class MemPage
- {
- public u8 isInit; /* True if previously initialized. MUST BE FIRST! */
- public u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
- public u8 intKey; /* True if u8key flag is set */
- public u8 leaf; /* 1 if leaf flag is set */
- public u8 hasData; /* True if this page stores data */
- public u8 hdrOffset; /* 100 for page 1. 0 otherwise */
- public u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
- public u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
- public u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
- public u16 cellOffset; /* Index in aData of first cell pou16er */
- public u16 nFree; /* Number of free bytes on the page */
- public u16 nCell; /* Number of cells on this page, local and ovfl */
- public u16 maskPage; /* Mask for page offset */
- public _OvflCell[] aOvfl = new _OvflCell[5];
- public BtShared pBt; /* Pointer to BtShared that this page is part of */
- public byte[] aData; /* Pointer to disk image of the page data */
- public DbPage pDbPage; /* Pager page handle */
- public Pgno pgno; /* Page number for this page */
-
- //public byte[] aData
- //{
- // get
- // {
- // Debug.Assert( pgno != 1 || pDbPage.pData == _aData );
- // return _aData;
- // }
- // set
- // {
- // _aData = value;
- // Debug.Assert( pgno != 1 || pDbPage.pData == _aData );
- // }
- //}
-
- public MemPage Copy()
- {
- MemPage cp = (MemPage)MemberwiseClone();
- if ( aOvfl != null )
- {
- cp.aOvfl = new _OvflCell[aOvfl.Length];
- for ( int i = 0; i < aOvfl.Length; i++ )
- cp.aOvfl[i] = aOvfl[i].Copy();
- }
- if ( aData != null )
- {
- cp.aData = sqlite3Malloc( aData.Length );
- Buffer.BlockCopy( aData, 0, cp.aData, 0, aData.Length );
- }
- return cp;
- }
- };
-
- /*
- ** The in-memory image of a disk page has the auxiliary information appended
- ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
- ** that extra information.
+ /*
+ ** Page type flags. An ORed combination of these flags appear as the
+ ** first byte of on-disk image of every BTree page.
*/
- const int EXTRA_SIZE = 0;// No used in C#, since we use create a class; was MemPage.Length;
-
- /*
- ** A linked list of the following structures is stored at BtShared.pLock.
- ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
- ** is opened on the table with root page BtShared.iTable. Locks are removed
- ** from this list when a transaction is committed or rolled back, or when
- ** a btree handle is closed.
- */
- public class BtLock
- {
- Btree pBtree; /* Btree handle holding this lock */
- Pgno iTable; /* Root page of table */
- u8 eLock; /* READ_LOCK or WRITE_LOCK */
- BtLock pNext; /* Next in BtShared.pLock list */
- };
-
- /* Candidate values for BtLock.eLock */
- //#define READ_LOCK 1
- //#define WRITE_LOCK 2
- const int READ_LOCK = 1;
- const int WRITE_LOCK = 2;
-
- /* A Btree handle
- **
- ** A database connection contains a pointer to an instance of
- ** this object for every database file that it has open. This structure
- ** is opaque to the database connection. The database connection cannot
- ** see the internals of this structure and only deals with pointers to
- ** this structure.
- **
- ** For some database files, the same underlying database cache might be
- ** shared between multiple connections. In that case, each connection
- ** has it own instance of this object. But each instance of this object
- ** points to the same BtShared object. The database cache and the
- ** schema associated with the database file are all contained within
- ** the BtShared object.
- **
- ** All fields in this structure are accessed under sqlite3.mutex.
- ** The pBt pointer itself may not be changed while there exists cursors
- ** in the referenced BtShared that point back to this Btree since those
- ** cursors have to go through this Btree to find their BtShared and
- ** they often do so without holding sqlite3.mutex.
- */
- public class Btree
- {
- public sqlite3 db; /* The database connection holding this Btree */
- public BtShared pBt; /* Sharable content of this Btree */
- public u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
- public bool sharable; /* True if we can share pBt with another db */
- public bool locked; /* True if db currently has pBt locked */
- public int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
- public int nBackup; /* Number of backup operations reading this btree */
- public Btree pNext; /* List of other sharable Btrees from the same db */
- public Btree pPrev; /* Back pointer of the same list */
+ const byte PTF_INTKEY = 0x01;
+ const byte PTF_ZERODATA = 0x02;
+ const byte PTF_LEAFDATA = 0x04;
+ const byte PTF_LEAF = 0x08;
+
+ /*
+ ** As each page of the file is loaded into memory, an instance of the following
+ ** structure is appended and initialized to zero. This structure stores
+ ** information about the page that is decoded from the raw file page.
+ **
+ ** The pParent field points back to the parent page. This allows us to
+ ** walk up the BTree from any leaf to the root. Care must be taken to
+ ** unref() the parent page pointer when this page is no longer referenced.
+ ** The pageDestructor() routine handles that chore.
+ **
+ ** Access to all fields of this structure is controlled by the mutex
+ ** stored in MemPage.pBt.mutex.
+ */
+ public struct _OvflCell { /* Cells that will not fit on aData[] */
+ public u8[] pCell; /* Pointers to the body of the overflow cell */
+ public u16 idx; /* Insert this cell before idx-th non-overflow cell */
+ public _OvflCell Copy() {
+ _OvflCell cp = new _OvflCell();
+ if (pCell != null) {
+ cp.pCell = sqlite3Malloc(pCell.Length);
+ Buffer.BlockCopy(pCell, 0, cp.pCell, 0, pCell.Length);
+ }
+ cp.idx = idx;
+ return cp;
+ }
+ };
+ public class MemPage {
+ public u8 isInit; /* True if previously initialized. MUST BE FIRST! */
+ public u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
+ public u8 intKey; /* True if u8key flag is set */
+ public u8 leaf; /* 1 if leaf flag is set */
+ public u8 hasData; /* True if this page stores data */
+ public u8 hdrOffset; /* 100 for page 1. 0 otherwise */
+ public u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
+ public u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
+ public u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
+ public u16 cellOffset; /* Index in aData of first cell pou16er */
+ public u16 nFree; /* Number of free bytes on the page */
+ public u16 nCell; /* Number of cells on this page, local and ovfl */
+ public u16 maskPage; /* Mask for page offset */
+ public _OvflCell[] aOvfl = new _OvflCell[5];
+ public BtShared pBt; /* Pointer to BtShared that this page is part of */
+ public byte[] aData; /* Pointer to disk image of the page data */
+ public DbPage pDbPage; /* Pager page handle */
+ public Pgno pgno; /* Page number for this page */
+
+ //public byte[] aData
+ //{
+ // get
+ // {
+ // Debug.Assert( pgno != 1 || pDbPage.pData == _aData );
+ // return _aData;
+ // }
+ // set
+ // {
+ // _aData = value;
+ // Debug.Assert( pgno != 1 || pDbPage.pData == _aData );
+ // }
+ //}
+
+ public MemPage Copy() {
+ MemPage cp = (MemPage)MemberwiseClone();
+ if (aOvfl != null) {
+ cp.aOvfl = new _OvflCell[aOvfl.Length];
+ for (int i = 0; i < aOvfl.Length; i++)
+ cp.aOvfl[i] = aOvfl[i].Copy();
+ }
+ if (aData != null) {
+ cp.aData = sqlite3Malloc(aData.Length);
+ Buffer.BlockCopy(aData, 0, cp.aData, 0, aData.Length);
+ }
+ return cp;
+ }
+ };
+
+ /*
+ ** The in-memory image of a disk page has the auxiliary information appended
+ ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
+ ** that extra information.
+ */
+ const int EXTRA_SIZE = 0;// No used in C#, since we use create a class; was MemPage.Length;
+
+ /*
+ ** A linked list of the following structures is stored at BtShared.pLock.
+ ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
+ ** is opened on the table with root page BtShared.iTable. Locks are removed
+ ** from this list when a transaction is committed or rolled back, or when
+ ** a btree handle is closed.
+ */
+ public class BtLock {
+ Btree pBtree; /* Btree handle holding this lock */
+ Pgno iTable; /* Root page of table */
+ u8 eLock; /* READ_LOCK or WRITE_LOCK */
+ BtLock pNext; /* Next in BtShared.pLock list */
+ };
+
+ /* Candidate values for BtLock.eLock */
+ //#define READ_LOCK 1
+ //#define WRITE_LOCK 2
+ const int READ_LOCK = 1;
+ const int WRITE_LOCK = 2;
+
+ /* A Btree handle
+ **
+ ** A database connection contains a pointer to an instance of
+ ** this object for every database file that it has open. This structure
+ ** is opaque to the database connection. The database connection cannot
+ ** see the internals of this structure and only deals with pointers to
+ ** this structure.
+ **
+ ** For some database files, the same underlying database cache might be
+ ** shared between multiple connections. In that case, each connection
+ ** has it own instance of this object. But each instance of this object
+ ** points to the same BtShared object. The database cache and the
+ ** schema associated with the database file are all contained within
+ ** the BtShared object.
+ **
+ ** All fields in this structure are accessed under sqlite3.mutex.
+ ** The pBt pointer itself may not be changed while there exists cursors
+ ** in the referenced BtShared that point back to this Btree since those
+ ** cursors have to go through this Btree to find their BtShared and
+ ** they often do so without holding sqlite3.mutex.
+ */
+ public class Btree {
+ public sqlite3 db; /* The database connection holding this Btree */
+ public BtShared pBt; /* Sharable content of this Btree */
+ public u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
+ public bool sharable; /* True if we can share pBt with another db */
+ public bool locked; /* True if db currently has pBt locked */
+ public int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
+ public int nBackup; /* Number of backup operations reading this btree */
+ public Btree pNext; /* List of other sharable Btrees from the same db */
+ public Btree pPrev; /* Back pointer of the same list */
#if !SQLITE_OMIT_SHARED_CACHE
BtLock lock; /* Object used to lock page 1 */
#endif
- };
-
- /*
- ** Btree.inTrans may take one of the following values.
- **
- ** If the shared-data extension is enabled, there may be multiple users
- ** of the Btree structure. At most one of these may open a write transaction,
- ** but any number may have active read transactions.
- */
- const byte TRANS_NONE = 0;
- const byte TRANS_READ = 1;
- const byte TRANS_WRITE = 2;
-
- /*
- ** An instance of this object represents a single database file.
- **
- ** A single database file can be in use as the same time by two
- ** or more database connections. When two or more connections are
- ** sharing the same database file, each connection has it own
- ** private Btree object for the file and each of those Btrees points
- ** to this one BtShared object. BtShared.nRef is the number of
- ** connections currently sharing this database file.
- **
- ** Fields in this structure are accessed under the BtShared.mutex
- ** mutex, except for nRef and pNext which are accessed under the
- ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
- ** may not be modified once it is initially set as long as nRef>0.
- ** The pSchema field may be set once under BtShared.mutex and
- ** thereafter is unchanged as long as nRef>0.
- **
- ** isPending:
- **
- ** If a BtShared client fails to obtain a write-lock on a database
- ** table (because there exists one or more read-locks on the table),
- ** the shared-cache enters 'pending-lock' state and isPending is
- ** set to true.
- **
- ** The shared-cache leaves the 'pending lock' state when either of
- ** the following occur:
- **
- ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
- ** 2) The number of locks held by other connections drops to zero.
- **
- ** while in the 'pending-lock' state, no connection may start a new
- ** transaction.
- **
- ** This feature is included to help prevent writer-starvation.
- */
- public class BtShared
- {
- public Pager pPager; /* The page cache */
- public sqlite3 db; /* Database connection currently using this Btree */
- public BtCursor pCursor; /* A list of all open cursors */
- public MemPage pPage1; /* First page of the database */
- public bool readOnly; /* True if the underlying file is readonly */
- public bool pageSizeFixed; /* True if the page size can no longer be changed */
- public bool secureDelete; /* True if secure_delete is enabled */
- public bool initiallyEmpty; /* Database is empty at start of transaction */
- public u8 openFlags; /* Flags to sqlite3BtreeOpen() */
+ };
+
+ /*
+ ** Btree.inTrans may take one of the following values.
+ **
+ ** If the shared-data extension is enabled, there may be multiple users
+ ** of the Btree structure. At most one of these may open a write transaction,
+ ** but any number may have active read transactions.
+ */
+ const byte TRANS_NONE = 0;
+ const byte TRANS_READ = 1;
+ const byte TRANS_WRITE = 2;
+
+ /*
+ ** An instance of this object represents a single database file.
+ **
+ ** A single database file can be in use as the same time by two
+ ** or more database connections. When two or more connections are
+ ** sharing the same database file, each connection has it own
+ ** private Btree object for the file and each of those Btrees points
+ ** to this one BtShared object. BtShared.nRef is the number of
+ ** connections currently sharing this database file.
+ **
+ ** Fields in this structure are accessed under the BtShared.mutex
+ ** mutex, except for nRef and pNext which are accessed under the
+ ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
+ ** may not be modified once it is initially set as long as nRef>0.
+ ** The pSchema field may be set once under BtShared.mutex and
+ ** thereafter is unchanged as long as nRef>0.
+ **
+ ** isPending:
+ **
+ ** If a BtShared client fails to obtain a write-lock on a database
+ ** table (because there exists one or more read-locks on the table),
+ ** the shared-cache enters 'pending-lock' state and isPending is
+ ** set to true.
+ **
+ ** The shared-cache leaves the 'pending lock' state when either of
+ ** the following occur:
+ **
+ ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
+ ** 2) The number of locks held by other connections drops to zero.
+ **
+ ** while in the 'pending-lock' state, no connection may start a new
+ ** transaction.
+ **
+ ** This feature is included to help prevent writer-starvation.
+ */
+ public class BtShared {
+ public Pager pPager; /* The page cache */
+ public sqlite3 db; /* Database connection currently using this Btree */
+ public BtCursor pCursor; /* A list of all open cursors */
+ public MemPage pPage1; /* First page of the database */
+ public bool readOnly; /* True if the underlying file is readonly */
+ public bool pageSizeFixed; /* True if the page size can no longer be changed */
+ public bool secureDelete; /* True if secure_delete is enabled */
+ public bool initiallyEmpty; /* Database is empty at start of transaction */
+ public u8 openFlags; /* Flags to sqlite3BtreeOpen() */
#if !SQLITE_OMIT_AUTOVACUUM
- public bool autoVacuum; /* True if auto-vacuum is enabled */
- public bool incrVacuum; /* True if incr-vacuum is enabled */
+ public bool autoVacuum; /* True if auto-vacuum is enabled */
+ public bool incrVacuum; /* True if incr-vacuum is enabled */
#endif
- public u8 inTransaction; /* Transaction state */
- public bool doNotUseWAL; /* If true, do not open write-ahead-log file */
- public u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
- public u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
- public u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
- public u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
- public u32 pageSize; /* Total number of bytes on a page */
- public u32 usableSize; /* Number of usable bytes on each page */
- public int nTransaction; /* Number of open transactions (read + write) */
- public Pgno nPage; /* Number of pages in the database */
- public Schema pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
- public dxFreeSchema xFreeSchema;/* Destructor for BtShared.pSchema */
- public sqlite3_mutex mutex; /* Non-recursive mutex required to access this object */
- public Bitvec pHasContent; /* Set of pages moved to free-list this transaction */
+ public u8 inTransaction; /* Transaction state */
+ public bool doNotUseWAL; /* If true, do not open write-ahead-log file */
+ public u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
+ public u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
+ public u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
+ public u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
+ public u32 pageSize; /* Total number of bytes on a page */
+ public u32 usableSize; /* Number of usable bytes on each page */
+ public int nTransaction; /* Number of open transactions (read + write) */
+ public Pgno nPage; /* Number of pages in the database */
+ public Schema pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
+ public dxFreeSchema xFreeSchema;/* Destructor for BtShared.pSchema */
+ public sqlite3_mutex mutex; /* Non-recursive mutex required to access this object */
+ public Bitvec pHasContent; /* Set of pages moved to free-list this transaction */
#if !SQLITE_OMIT_SHARED_CACHE
public int nRef; /* Number of references to this structure */
public BtShared pNext; /* Next on a list of sharable BtShared structs */
@@ -520,304 +504,290 @@ public class BtShared
public u8 isExclusive; /* True if pWriter has an EXCLUSIVE lock on the db */
public u8 isPending; /* If waiting for read-locks to clear */
#endif
- public byte[] pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
- };
-
- /*
- ** An instance of the following structure is used to hold information
- ** about a cell. The parseCellPtr() function fills in this structure
- ** based on information extract from the raw disk page.
- */
- //typedef struct CellInfo CellInfo;
- public struct CellInfo
- {
- public int iCell; /* Offset to start of cell content -- Needed for C# */
- public byte[] pCell; /* Pointer to the start of cell content */
- public i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
- public u32 nData; /* Number of bytes of data */
- public u32 nPayload; /* Total amount of payload */
- public u16 nHeader; /* Size of the cell content header in bytes */
- public u16 nLocal; /* Amount of payload held locally */
- public u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
- public u16 nSize; /* Size of the cell content on the main b-tree page */
- public bool Equals( CellInfo ci )
- {
- if ( ci.iCell >= ci.pCell.Length || iCell >= this.pCell.Length )
- return false;
- if ( ci.pCell[ci.iCell] != this.pCell[iCell] )
- return false;
- if ( ci.nKey != this.nKey || ci.nData != this.nData || ci.nPayload != this.nPayload )
- return false;
- if ( ci.nHeader != this.nHeader || ci.nLocal != this.nLocal )
- return false;
- if ( ci.iOverflow != this.iOverflow || ci.nSize != this.nSize )
- return false;
- return true;
- }
- };
-
- /*
- ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
- ** this will be declared corrupt. This value is calculated based on a
- ** maximum database size of 2^31 pages a minimum fanout of 2 for a
- ** root-node and 3 for all other internal nodes.
- **
- ** If a tree that appears to be taller than this is encountered, it is
- ** assumed that the database is corrupt.
- */
- //#define BTCURSOR_MAX_DEPTH 20
- const int BTCURSOR_MAX_DEPTH = 20;
-
- /*
- ** A cursor is a pointer to a particular entry within a particular
- ** b-tree within a database file.
- **
- ** The entry is identified by its MemPage and the index in
- ** MemPage.aCell[] of the entry.
- **
- ** A single database file can shared by two more database connections,
- ** but cursors cannot be shared. Each cursor is associated with a
- ** particular database connection identified BtCursor.pBtree.db.
- **
- ** Fields in this structure are accessed under the BtShared.mutex
- ** found at self.pBt.mutex.
- */
- public class BtCursor
- {
- public Btree pBtree; /* The Btree to which this cursor belongs */
- public BtShared pBt; /* The BtShared this cursor points to */
- public BtCursor pNext;
- public BtCursor pPrev; /* Forms a linked list of all cursors */
- public KeyInfo pKeyInfo; /* Argument passed to comparison function */
- public Pgno pgnoRoot; /* The root page of this tree */
- public sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
- public CellInfo info = new CellInfo(); /* A parse of the cell we are pointing at */
- public byte[] pKey; /* Saved key that was cursor's last known position */
- public i64 nKey; /* Size of pKey, or last integer key */
- public int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
- public u8 wrFlag; /* True if writable */
- public u8 atLast; /* VdbeCursor pointing to the last entry */
- public bool validNKey; /* True if info.nKey is valid */
- public int eState; /* One of the CURSOR_XXX constants (see below) */
+ public byte[] pTmpSpace; /* BtShared.pageSize bytes of space for tmp use */
+ };
+
+ /*
+ ** An instance of the following structure is used to hold information
+ ** about a cell. The parseCellPtr() function fills in this structure
+ ** based on information extract from the raw disk page.
+ */
+ //typedef struct CellInfo CellInfo;
+ public struct CellInfo {
+ public int iCell; /* Offset to start of cell content -- Needed for C# */
+ public byte[] pCell; /* Pointer to the start of cell content */
+ public i64 nKey; /* The key for INTKEY tables, or number of bytes in key */
+ public u32 nData; /* Number of bytes of data */
+ public u32 nPayload; /* Total amount of payload */
+ public u16 nHeader; /* Size of the cell content header in bytes */
+ public u16 nLocal; /* Amount of payload held locally */
+ public u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
+ public u16 nSize; /* Size of the cell content on the main b-tree page */
+ public bool Equals(CellInfo ci) {
+ if (ci.iCell >= ci.pCell.Length || iCell >= this.pCell.Length)
+ return false;
+ if (ci.pCell[ci.iCell] != this.pCell[iCell])
+ return false;
+ if (ci.nKey != this.nKey || ci.nData != this.nData || ci.nPayload != this.nPayload)
+ return false;
+ if (ci.nHeader != this.nHeader || ci.nLocal != this.nLocal)
+ return false;
+ if (ci.iOverflow != this.iOverflow || ci.nSize != this.nSize)
+ return false;
+ return true;
+ }
+ };
+
+ /*
+ ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
+ ** this will be declared corrupt. This value is calculated based on a
+ ** maximum database size of 2^31 pages a minimum fanout of 2 for a
+ ** root-node and 3 for all other internal nodes.
+ **
+ ** If a tree that appears to be taller than this is encountered, it is
+ ** assumed that the database is corrupt.
+ */
+ //#define BTCURSOR_MAX_DEPTH 20
+ const int BTCURSOR_MAX_DEPTH = 20;
+
+ /*
+ ** A cursor is a pointer to a particular entry within a particular
+ ** b-tree within a database file.
+ **
+ ** The entry is identified by its MemPage and the index in
+ ** MemPage.aCell[] of the entry.
+ **
+ ** A single database file can shared by two more database connections,
+ ** but cursors cannot be shared. Each cursor is associated with a
+ ** particular database connection identified BtCursor.pBtree.db.
+ **
+ ** Fields in this structure are accessed under the BtShared.mutex
+ ** found at self.pBt.mutex.
+ */
+ public class BtCursor {
+ public Btree pBtree; /* The Btree to which this cursor belongs */
+ public BtShared pBt; /* The BtShared this cursor points to */
+ public BtCursor pNext;
+ public BtCursor pPrev; /* Forms a linked list of all cursors */
+ public KeyInfo pKeyInfo; /* Argument passed to comparison function */
+ public Pgno pgnoRoot; /* The root page of this tree */
+ public sqlite3_int64 cachedRowid; /* Next rowid cache. 0 means not valid */
+ public CellInfo info = new CellInfo(); /* A parse of the cell we are pointing at */
+ public byte[] pKey; /* Saved key that was cursor's last known position */
+ public i64 nKey; /* Size of pKey, or last integer key */
+ public int skipNext; /* Prev() is noop if negative. Next() is noop if positive */
+ public u8 wrFlag; /* True if writable */
+ public u8 atLast; /* VdbeCursor pointing to the last entry */
+ public bool validNKey; /* True if info.nKey is valid */
+ public int eState; /* One of the CURSOR_XXX constants (see below) */
#if !SQLITE_OMIT_INCRBLOB
public Pgno[] aOverflow; /* Cache of overflow page locations */
public bool isIncrblobHandle; /* True if this cursor is an incr. io handle */
#endif
- public i16 iPage; /* Index of current page in apPage */
- public u16[] aiIdx = new u16[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
- public MemPage[] apPage = new MemPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
-
- public void Clear()
- {
- pNext = null;
- pPrev = null;
- pKeyInfo = null;
- pgnoRoot = 0;
- cachedRowid = 0;
- info = new CellInfo();
- wrFlag = 0;
- atLast = 0;
- validNKey = false;
- eState = 0;
- pKey = null;
- nKey = 0;
- skipNext = 0;
+ public i16 iPage; /* Index of current page in apPage */
+ public u16[] aiIdx = new u16[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
+ public MemPage[] apPage = new MemPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
+
+ public void Clear() {
+ pNext = null;
+ pPrev = null;
+ pKeyInfo = null;
+ pgnoRoot = 0;
+ cachedRowid = 0;
+ info = new CellInfo();
+ wrFlag = 0;
+ atLast = 0;
+ validNKey = false;
+ eState = 0;
+ pKey = null;
+ nKey = 0;
+ skipNext = 0;
#if !SQLITE_OMIT_INCRBLOB
isIncrblobHandle=false;
aOverflow= null;
#endif
- iPage = 0;
- }
- public BtCursor Copy()
- {
- BtCursor cp = (BtCursor)MemberwiseClone();
- return cp;
- }
- };
-
- /*
- ** Potential values for BtCursor.eState.
- **
- ** CURSOR_VALID:
- ** VdbeCursor points to a valid entry. getPayload() etc. may be called.
- **
- ** CURSOR_INVALID:
- ** VdbeCursor does not point to a valid entry. This can happen (for example)
- ** because the table is empty or because BtreeCursorFirst() has not been
- ** called.
- **
- ** CURSOR_REQUIRESEEK:
- ** The table that this cursor was opened on still exists, but has been
- ** modified since the cursor was last used. The cursor position is saved
- ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
- ** this state, restoreCursorPosition() can be called to attempt to
- ** seek the cursor to the saved position.
- **
- ** CURSOR_FAULT:
- ** A unrecoverable error (an I/O error or a malloc failure) has occurred
- ** on a different connection that shares the BtShared cache with this
- ** cursor. The error has left the cache in an inconsistent state.
- ** Do nothing else with this cursor. Any attempt to use the cursor
- ** should return the error code stored in BtCursor.skip
- */
- const int CURSOR_INVALID = 0;
- const int CURSOR_VALID = 1;
- const int CURSOR_REQUIRESEEK = 2;
- const int CURSOR_FAULT = 3;
-
- /*
- ** The database page the PENDING_BYTE occupies. This page is never used.
- */
- //# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
- // TODO -- Convert PENDING_BYTE_PAGE to inline
- static u32 PENDING_BYTE_PAGE( BtShared pBt )
- {
- return (u32)PAGER_MJ_PGNO( pBt.pPager );
- }
+ iPage = 0;
+ }
+ public BtCursor Copy() {
+ BtCursor cp = (BtCursor)MemberwiseClone();
+ return cp;
+ }
+ };
+
+ /*
+ ** Potential values for BtCursor.eState.
+ **
+ ** CURSOR_VALID:
+ ** VdbeCursor points to a valid entry. getPayload() etc. may be called.
+ **
+ ** CURSOR_INVALID:
+ ** VdbeCursor does not point to a valid entry. This can happen (for example)
+ ** because the table is empty or because BtreeCursorFirst() has not been
+ ** called.
+ **
+ ** CURSOR_REQUIRESEEK:
+ ** The table that this cursor was opened on still exists, but has been
+ ** modified since the cursor was last used. The cursor position is saved
+ ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
+ ** this state, restoreCursorPosition() can be called to attempt to
+ ** seek the cursor to the saved position.
+ **
+ ** CURSOR_FAULT:
+ ** A unrecoverable error (an I/O error or a malloc failure) has occurred
+ ** on a different connection that shares the BtShared cache with this
+ ** cursor. The error has left the cache in an inconsistent state.
+ ** Do nothing else with this cursor. Any attempt to use the cursor
+ ** should return the error code stored in BtCursor.skip
+ */
+ const int CURSOR_INVALID = 0;
+ const int CURSOR_VALID = 1;
+ const int CURSOR_REQUIRESEEK = 2;
+ const int CURSOR_FAULT = 3;
+
+ /*
+ ** The database page the PENDING_BYTE occupies. This page is never used.
+ */
+ //# define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
+ // TODO -- Convert PENDING_BYTE_PAGE to inline
+ static u32 PENDING_BYTE_PAGE(BtShared pBt) {
+ return (u32)PAGER_MJ_PGNO(pBt.pPager);
+ }
- /*
- ** These macros define the location of the pointer-map entry for a
- ** database page. The first argument to each is the number of usable
- ** bytes on each page of the database (often 1024). The second is the
- ** page number to look up in the pointer map.
- **
- ** PTRMAP_PAGENO returns the database page number of the pointer-map
- ** page that stores the required pointer. PTRMAP_PTROFFSET returns
- ** the offset of the requested map entry.
- **
- ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
- ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
- ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
- ** this test.
- */
- //#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
- static Pgno PTRMAP_PAGENO( BtShared pBt, Pgno pgno )
- {
- return ptrmapPageno( pBt, pgno );
- }
- //#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
- static u32 PTRMAP_PTROFFSET( u32 pgptrmap, u32 pgno )
- {
- return ( 5 * ( pgno - pgptrmap - 1 ) );
- }
- //#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
- static bool PTRMAP_ISPAGE( BtShared pBt, u32 pgno )
- {
- return ( PTRMAP_PAGENO( ( pBt ), ( pgno ) ) == ( pgno ) );
- }
- /*
- ** The pointer map is a lookup table that identifies the parent page for
- ** each child page in the database file. The parent page is the page that
- ** contains a pointer to the child. Every page in the database contains
- ** 0 or 1 parent pages. (In this context 'database page' refers
- ** to any page that is not part of the pointer map itself.) Each pointer map
- ** entry consists of a single byte 'type' and a 4 byte parent page number.
- ** The PTRMAP_XXX identifiers below are the valid types.
- **
- ** The purpose of the pointer map is to facility moving pages from one
- ** position in the file to another as part of autovacuum. When a page
- ** is moved, the pointer in its parent must be updated to point to the
- ** new location. The pointer map is used to locate the parent page quickly.
- **
- ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
- ** used in this case.
- **
- ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
- ** is not used in this case.
- **
- ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
- ** overflow pages. The page number identifies the page that
- ** contains the cell with a pointer to this overflow page.
- **
- ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
- ** overflow pages. The page-number identifies the previous
- ** page in the overflow page list.
- **
- ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
- ** identifies the parent page in the btree.
- */
- //#define PTRMAP_ROOTPAGE 1
- //#define PTRMAP_FREEPAGE 2
- //#define PTRMAP_OVERFLOW1 3
- //#define PTRMAP_OVERFLOW2 4
- //#define PTRMAP_BTREE 5
- const int PTRMAP_ROOTPAGE = 1;
- const int PTRMAP_FREEPAGE = 2;
- const int PTRMAP_OVERFLOW1 = 3;
- const int PTRMAP_OVERFLOW2 = 4;
- const int PTRMAP_BTREE = 5;
-
- /* A bunch of Debug.Assert() statements to check the transaction state variables
- ** of handle p (type Btree*) are internally consistent.
- */
+ /*
+ ** These macros define the location of the pointer-map entry for a
+ ** database page. The first argument to each is the number of usable
+ ** bytes on each page of the database (often 1024). The second is the
+ ** page number to look up in the pointer map.
+ **
+ ** PTRMAP_PAGENO returns the database page number of the pointer-map
+ ** page that stores the required pointer. PTRMAP_PTROFFSET returns
+ ** the offset of the requested map entry.
+ **
+ ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
+ ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
+ ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
+ ** this test.
+ */
+ //#define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
+ static Pgno PTRMAP_PAGENO(BtShared pBt, Pgno pgno) {
+ return ptrmapPageno(pBt, pgno);
+ }
+ //#define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
+ static u32 PTRMAP_PTROFFSET(u32 pgptrmap, u32 pgno) {
+ return (5 * (pgno - pgptrmap - 1));
+ }
+ //#define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
+ static bool PTRMAP_ISPAGE(BtShared pBt, u32 pgno) {
+ return (PTRMAP_PAGENO((pBt), (pgno)) == (pgno));
+ }
+ /*
+ ** The pointer map is a lookup table that identifies the parent page for
+ ** each child page in the database file. The parent page is the page that
+ ** contains a pointer to the child. Every page in the database contains
+ ** 0 or 1 parent pages. (In this context 'database page' refers
+ ** to any page that is not part of the pointer map itself.) Each pointer map
+ ** entry consists of a single byte 'type' and a 4 byte parent page number.
+ ** The PTRMAP_XXX identifiers below are the valid types.
+ **
+ ** The purpose of the pointer map is to facility moving pages from one
+ ** position in the file to another as part of autovacuum. When a page
+ ** is moved, the pointer in its parent must be updated to point to the
+ ** new location. The pointer map is used to locate the parent page quickly.
+ **
+ ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
+ ** used in this case.
+ **
+ ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
+ ** is not used in this case.
+ **
+ ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
+ ** overflow pages. The page number identifies the page that
+ ** contains the cell with a pointer to this overflow page.
+ **
+ ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
+ ** overflow pages. The page-number identifies the previous
+ ** page in the overflow page list.
+ **
+ ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
+ ** identifies the parent page in the btree.
+ */
+ //#define PTRMAP_ROOTPAGE 1
+ //#define PTRMAP_FREEPAGE 2
+ //#define PTRMAP_OVERFLOW1 3
+ //#define PTRMAP_OVERFLOW2 4
+ //#define PTRMAP_BTREE 5
+ const int PTRMAP_ROOTPAGE = 1;
+ const int PTRMAP_FREEPAGE = 2;
+ const int PTRMAP_OVERFLOW1 = 3;
+ const int PTRMAP_OVERFLOW2 = 4;
+ const int PTRMAP_BTREE = 5;
+
+ /* A bunch of Debug.Assert() statements to check the transaction state variables
+ ** of handle p (type Btree*) are internally consistent.
+ */
#if DEBUG
- //#define btreeIntegrity(p) \
- // Debug.Assert( p.pBt.inTransaction!=TRANS_NONE || p.pBt.nTransaction==0 ); \
- // Debug.Assert( p.pBt.inTransaction>=p.inTrans );
- static void btreeIntegrity( Btree p )
- {
- Debug.Assert( p.pBt.inTransaction != TRANS_NONE || p.pBt.nTransaction == 0 );
- Debug.Assert( p.pBt.inTransaction >= p.inTrans );
- }
+ //#define btreeIntegrity(p) \
+ // Debug.Assert( p.pBt.inTransaction!=TRANS_NONE || p.pBt.nTransaction==0 ); \
+ // Debug.Assert( p.pBt.inTransaction>=p.inTrans );
+ static void btreeIntegrity(Btree p) {
+ Debug.Assert(p.pBt.inTransaction != TRANS_NONE || p.pBt.nTransaction == 0);
+ Debug.Assert(p.pBt.inTransaction >= p.inTrans);
+ }
#else
static void btreeIntegrity(Btree p) { }
#endif
- /*
-** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
-** if the database supports auto-vacuum or not. Because it is used
-** within an expression that is an argument to another macro
-** (sqliteMallocRaw), it is not possible to use conditional compilation.
-** So, this macro is defined instead.
-*/
+ /*
+ ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
+ ** if the database supports auto-vacuum or not. Because it is used
+ ** within an expression that is an argument to another macro
+ ** (sqliteMallocRaw), it is not possible to use conditional compilation.
+ ** So, this macro is defined instead.
+ */
#if !SQLITE_OMIT_AUTOVACUUM
- //#define ISAUTOVACUUM (pBt.autoVacuum)
+ //#define ISAUTOVACUUM (pBt.autoVacuum)
#else
//#define ISAUTOVACUUM 0
public static bool ISAUTOVACUUM =false;
#endif
- /*
-** This structure is passed around through all the sanity checking routines
-** in order to keep track of some global state information.
-*/
- //typedef struct IntegrityCk IntegrityCk;
- public class IntegrityCk
- {
- public BtShared pBt; /* The tree being checked out */
- public Pager pPager; /* The associated pager. Also accessible by pBt.pPager */
- public Pgno nPage; /* Number of pages in the database */
- public int[] anRef; /* Number of times each page is referenced */
- public int mxErr; /* Stop accumulating errors when this reaches zero */
- public int nErr; /* Number of messages written to zErrMsg so far */
- //public int mallocFailed; /* A memory allocation error has occurred */
- public StrAccum errMsg = new StrAccum( 100 ); /* Accumulate the error message text here */
- };
-
- /*
- ** Read or write a two- and four-byte big-endian integer values.
+ /*
+ ** This structure is passed around through all the sanity checking routines
+ ** in order to keep track of some global state information.
*/
- //#define get2byte(x) ((x)[0]<<8 | (x)[1])
- static int get2byte( byte[] p, int offset )
- {
- return p[offset + 0] << 8 | p[offset + 1];
- }
+ //typedef struct IntegrityCk IntegrityCk;
+ public class IntegrityCk {
+ public BtShared pBt; /* The tree being checked out */
+ public Pager pPager; /* The associated pager. Also accessible by pBt.pPager */
+ public Pgno nPage; /* Number of pages in the database */
+ public int[] anRef; /* Number of times each page is referenced */
+ public int mxErr; /* Stop accumulating errors when this reaches zero */
+ public int nErr; /* Number of messages written to zErrMsg so far */
+ //public int mallocFailed; /* A memory allocation error has occurred */
+ public StrAccum errMsg = new StrAccum(100); /* Accumulate the error message text here */
+ };
+
+ /*
+ ** Read or write a two- and four-byte big-endian integer values.
+ */
+ //#define get2byte(x) ((x)[0]<<8 | (x)[1])
+ static int get2byte(byte[] p, int offset) {
+ return p[offset + 0] << 8 | p[offset + 1];
+ }
- //#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
- static void put2byte( byte[] pData, int Offset, u32 v )
- {
- pData[Offset + 0] = (byte)( v >> 8 );
- pData[Offset + 1] = (byte)v;
- }
- static void put2byte( byte[] pData, int Offset, int v )
- {
- pData[Offset + 0] = (byte)( v >> 8 );
- pData[Offset + 1] = (byte)v;
- }
+ //#define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
+ static void put2byte(byte[] pData, int Offset, u32 v) {
+ pData[Offset + 0] = (byte)(v >> 8);
+ pData[Offset + 1] = (byte)v;
+ }
+ static void put2byte(byte[] pData, int Offset, int v) {
+ pData[Offset + 0] = (byte)(v >> 8);
+ pData[Offset + 1] = (byte)v;
+ }
- //#define get4byte sqlite3Get4byte
- //#define put4byte sqlite3Put4byte
+ //#define get4byte sqlite3Get4byte
+ //#define put4byte sqlite3Put4byte
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/Btree_h.cs b/Src/IronPython.SQLite/c#sqlite/Btree_h.cs
index 996516f23..688165138 100644
--- a/Src/IronPython.SQLite/c#sqlite/Btree_h.cs
+++ b/Src/IronPython.SQLite/c#sqlite/Btree_h.cs
@@ -1,247 +1,243 @@
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This header file defines the interface that the sqlite B-Tree file
- ** subsystem. See comments in the source code for a detailed description
- ** of what each interface routine does.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#if !_BTREE_H_
- //#define _BTREE_H_
-
- /* TODO: This definition is just included so other modules compile. It
- ** needs to be revisited.
- */
- const int SQLITE_N_BTREE_META = 10;
-
- /*
- ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
- ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
- */
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This header file defines the interface that the sqlite B-Tree file
+ ** subsystem. See comments in the source code for a detailed description
+ ** of what each interface routine does.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#if !_BTREE_H_
+ //#define _BTREE_H_
+
+ /* TODO: This definition is just included so other modules compile. It
+ ** needs to be revisited.
+ */
+ const int SQLITE_N_BTREE_META = 10;
+
+ /*
+ ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
+ ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
+ */
#if !SQLITE_DEFAULT_AUTOVACUUM
- const int SQLITE_DEFAULT_AUTOVACUUM = 0;
+ const int SQLITE_DEFAULT_AUTOVACUUM = 0;
#endif
- const int BTREE_AUTOVACUUM_NONE = 0; /* Do not do auto-vacuum */
- const int BTREE_AUTOVACUUM_FULL = 1; /* Do full auto-vacuum */
- const int BTREE_AUTOVACUUM_INCR = 2; /* Incremental vacuum */
-
- /*
- ** Forward declarations of structure
- */
- //typedef struct Btree Btree;
- //typedef struct BtCursor BtCursor;
- //typedef struct BtShared BtShared;
-
- //int sqlite3BtreeOpen(
- // sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
- // string zFilename, /* Name of database file to open */
- // sqlite3 db, /* Associated database connection */
- // Btree **ppBtree, /* Return open Btree* here */
- // int flags, /* Flags */
- // int vfsFlags /* Flags passed through to VFS open */
- //);
-
- /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
- ** following values.
- **
- ** NOTE: These values must match the corresponding PAGER_ values in
- ** pager.h.
- */
- //#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
- //#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
- //#define BTREE_MEMORY 4 /* This is an in-memory DB */
- //#define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
- //#define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
- const int BTREE_OMIT_JOURNAL = 1; /* Do not create or use a rollback journal */
- const int BTREE_NO_READLOCK = 2; /* Omit readlocks on readonly files */
- const int BTREE_MEMORY = 4; /* This is an in-memory DB */
- const int BTREE_SINGLE = 8; /* The file contains at most 1 b-tree */
- const int BTREE_UNORDERED = 16; /* Use of a hash implementation is OK */
-
- //int sqlite3BtreeClose(Btree);
- //int sqlite3BtreeSetCacheSize(Btree*,int);
- //int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
- //int sqlite3BtreeSyncDisabled(Btree);
- //int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
- //int sqlite3BtreeGetPageSize(Btree);
- //int sqlite3BtreeMaxPageCount(Btree*,int);
- //u32 sqlite3BtreeLastPage(Btree);
- //int sqlite3BtreeSecureDelete(Btree*,int);
- //int sqlite3BtreeGetReserve(Btree);
- //int sqlite3BtreeSetAutoVacuum(Btree , int);
- //int sqlite3BtreeGetAutoVacuum(Btree );
- //int sqlite3BtreeBeginTrans(Btree*,int);
- //int sqlite3BtreeCommitPhaseOne(Btree*, string zMaster);
- //int sqlite3BtreeCommitPhaseTwo(Btree*, int);
- //int sqlite3BtreeCommit(Btree);
- //int sqlite3BtreeRollback(Btree);
- //int sqlite3BtreeBeginStmt(Btree);
- //int sqlite3BtreeCreateTable(Btree*, int*, int flags);
- //int sqlite3BtreeIsInTrans(Btree);
- //int sqlite3BtreeIsInReadTrans(Btree);
- //int sqlite3BtreeIsInBackup(Btree);
- //void *sqlite3BtreeSchema(Btree , int, void()(void ));
- //int sqlite3BtreeSchemaLocked( Btree* pBtree );
- //int sqlite3BtreeLockTable( Btree* pBtree, int iTab, u8 isWriteLock );
- //int sqlite3BtreeSavepoint(Btree *, int, int);
-
- //string sqlite3BtreeGetFilename(Btree );
- //string sqlite3BtreeGetJournalname(Btree );
- //int sqlite3BtreeCopyFile(Btree *, Btree );
-
- //int sqlite3BtreeIncrVacuum(Btree );
-
- /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
- ** of the flags shown below.
- **
- ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
- ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
- ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
- ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
- ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
- ** indices.)
- */
- //#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
- //#define BTREE_BLOBKEY 2 /* Table has keys only - no data */
- const int BTREE_INTKEY = 1;
- const int BTREE_BLOBKEY = 2;
-
- //int sqlite3BtreeDropTable(Btree*, int, int);
- //int sqlite3BtreeClearTable(Btree*, int, int);
- //void sqlite3BtreeTripAllCursors(Btree*, int);
-
- //void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
- //int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
-
-
- /*
- ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
- ** should be one of the following values. The integer values are assigned
- ** to constants so that the offset of the corresponding field in an
- ** SQLite database header may be found using the following formula:
- **
- ** offset = 36 + (idx * 4)
- **
- ** For example, the free-page-count field is located at byte offset 36 of
- ** the database file header. The incr-vacuum-flag field is located at
- ** byte offset 64 (== 36+4*7).
- */
- //#define BTREE_FREE_PAGE_COUNT 0
- //#define BTREE_SCHEMA_VERSION 1
- //#define BTREE_FILE_FORMAT 2
- //#define BTREE_DEFAULT_CACHE_SIZE 3
- //#define BTREE_LARGEST_ROOT_PAGE 4
- //#define BTREE_TEXT_ENCODING 5
- //#define BTREE_USER_VERSION 6
- //#define BTREE_INCR_VACUUM 7
- const int BTREE_FREE_PAGE_COUNT = 0;
- const int BTREE_SCHEMA_VERSION = 1;
- const int BTREE_FILE_FORMAT = 2;
- const int BTREE_DEFAULT_CACHE_SIZE = 3;
- const int BTREE_LARGEST_ROOT_PAGE = 4;
- const int BTREE_TEXT_ENCODING = 5;
- const int BTREE_USER_VERSION = 6;
- const int BTREE_INCR_VACUUM = 7;
-
- //int sqlite3BtreeCursor(
- // Btree*, /* BTree containing table to open */
- // int iTable, /* Index of root page */
- // int wrFlag, /* 1 for writing. 0 for read-only */
- // struct KeyInfo*, /* First argument to compare function */
- // BtCursor pCursor /* Space to write cursor structure */
- //);
- //int sqlite3BtreeCursorSize(void);
- //void sqlite3BtreeCursorZero(BtCursor);
-
- //int sqlite3BtreeCloseCursor(BtCursor);
- //int sqlite3BtreeMovetoUnpacked(
- // BtCursor*,
- // UnpackedRecord pUnKey,
- // i64 intKey,
- // int bias,
- // int pRes
- //);
- //int sqlite3BtreeCursorHasMoved(BtCursor*, int);
- //int sqlite3BtreeDelete(BtCursor);
- //int sqlite3BtreeInsert(BtCursor*, const void pKey, i64 nKey,
- // const void pData, int nData,
- // int nZero, int bias, int seekResult);
- //int sqlite3BtreeFirst(BtCursor*, int pRes);
- //int sqlite3BtreeLast(BtCursor*, int pRes);
- //int sqlite3BtreeNext(BtCursor*, int pRes);
- //int sqlite3BtreeEof(BtCursor);
- //int sqlite3BtreePrevious(BtCursor*, int pRes);
- //int sqlite3BtreeKeySize(BtCursor*, i64 pSize);
- //int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void);
- //const void *sqlite3BtreeKeyFetch(BtCursor*, int pAmt);
- //const void *sqlite3BtreeDataFetch(BtCursor*, int pAmt);
- //int sqlite3BtreeDataSize(BtCursor*, u32 pSize);
- //int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void);
- //void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
- //sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor);
-
- //char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int);
- //struct Pager *sqlite3BtreePager(Btree);
-
- //int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void);
- //void sqlite3BtreeCacheOverflow(BtCursor );
- //void sqlite3BtreeClearCursor(BtCursor );
-
- //int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
-
- //#if !NDEBUG
- //int sqlite3BtreeCursorIsValid(BtCursor);
- //#endif
-
- //#if !SQLITE_OMIT_BTREECOUNT
- //int sqlite3BtreeCount(BtCursor *, i64 );
- //#endif
-
- //#if SQLITE_TEST
- //int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
- //void sqlite3BtreeCursorList(Btree);
- //#endif
+ const int BTREE_AUTOVACUUM_NONE = 0; /* Do not do auto-vacuum */
+ const int BTREE_AUTOVACUUM_FULL = 1; /* Do full auto-vacuum */
+ const int BTREE_AUTOVACUUM_INCR = 2; /* Incremental vacuum */
+
+ /*
+ ** Forward declarations of structure
+ */
+ //typedef struct Btree Btree;
+ //typedef struct BtCursor BtCursor;
+ //typedef struct BtShared BtShared;
+
+ //int sqlite3BtreeOpen(
+ // sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
+ // string zFilename, /* Name of database file to open */
+ // sqlite3 db, /* Associated database connection */
+ // Btree **ppBtree, /* Return open Btree* here */
+ // int flags, /* Flags */
+ // int vfsFlags /* Flags passed through to VFS open */
+ //);
+
+ /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
+ ** following values.
+ **
+ ** NOTE: These values must match the corresponding PAGER_ values in
+ ** pager.h.
+ */
+ //#define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
+ //#define BTREE_NO_READLOCK 2 /* Omit readlocks on readonly files */
+ //#define BTREE_MEMORY 4 /* This is an in-memory DB */
+ //#define BTREE_SINGLE 8 /* The file contains at most 1 b-tree */
+ //#define BTREE_UNORDERED 16 /* Use of a hash implementation is OK */
+ const int BTREE_OMIT_JOURNAL = 1; /* Do not create or use a rollback journal */
+ const int BTREE_NO_READLOCK = 2; /* Omit readlocks on readonly files */
+ const int BTREE_MEMORY = 4; /* This is an in-memory DB */
+ const int BTREE_SINGLE = 8; /* The file contains at most 1 b-tree */
+ const int BTREE_UNORDERED = 16; /* Use of a hash implementation is OK */
+
+ //int sqlite3BtreeClose(Btree);
+ //int sqlite3BtreeSetCacheSize(Btree*,int);
+ //int sqlite3BtreeSetSafetyLevel(Btree*,int,int,int);
+ //int sqlite3BtreeSyncDisabled(Btree);
+ //int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
+ //int sqlite3BtreeGetPageSize(Btree);
+ //int sqlite3BtreeMaxPageCount(Btree*,int);
+ //u32 sqlite3BtreeLastPage(Btree);
+ //int sqlite3BtreeSecureDelete(Btree*,int);
+ //int sqlite3BtreeGetReserve(Btree);
+ //int sqlite3BtreeSetAutoVacuum(Btree , int);
+ //int sqlite3BtreeGetAutoVacuum(Btree );
+ //int sqlite3BtreeBeginTrans(Btree*,int);
+ //int sqlite3BtreeCommitPhaseOne(Btree*, string zMaster);
+ //int sqlite3BtreeCommitPhaseTwo(Btree*, int);
+ //int sqlite3BtreeCommit(Btree);
+ //int sqlite3BtreeRollback(Btree);
+ //int sqlite3BtreeBeginStmt(Btree);
+ //int sqlite3BtreeCreateTable(Btree*, int*, int flags);
+ //int sqlite3BtreeIsInTrans(Btree);
+ //int sqlite3BtreeIsInReadTrans(Btree);
+ //int sqlite3BtreeIsInBackup(Btree);
+ //void *sqlite3BtreeSchema(Btree , int, void()(void ));
+ //int sqlite3BtreeSchemaLocked( Btree* pBtree );
+ //int sqlite3BtreeLockTable( Btree* pBtree, int iTab, u8 isWriteLock );
+ //int sqlite3BtreeSavepoint(Btree *, int, int);
+
+ //string sqlite3BtreeGetFilename(Btree );
+ //string sqlite3BtreeGetJournalname(Btree );
+ //int sqlite3BtreeCopyFile(Btree *, Btree );
+
+ //int sqlite3BtreeIncrVacuum(Btree );
+
+ /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
+ ** of the flags shown below.
+ **
+ ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
+ ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
+ ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
+ ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
+ ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
+ ** indices.)
+ */
+ //#define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
+ //#define BTREE_BLOBKEY 2 /* Table has keys only - no data */
+ const int BTREE_INTKEY = 1;
+ const int BTREE_BLOBKEY = 2;
+
+ //int sqlite3BtreeDropTable(Btree*, int, int);
+ //int sqlite3BtreeClearTable(Btree*, int, int);
+ //void sqlite3BtreeTripAllCursors(Btree*, int);
+
+ //void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
+ //int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
+
+
+ /*
+ ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
+ ** should be one of the following values. The integer values are assigned
+ ** to constants so that the offset of the corresponding field in an
+ ** SQLite database header may be found using the following formula:
+ **
+ ** offset = 36 + (idx * 4)
+ **
+ ** For example, the free-page-count field is located at byte offset 36 of
+ ** the database file header. The incr-vacuum-flag field is located at
+ ** byte offset 64 (== 36+4*7).
+ */
+ //#define BTREE_FREE_PAGE_COUNT 0
+ //#define BTREE_SCHEMA_VERSION 1
+ //#define BTREE_FILE_FORMAT 2
+ //#define BTREE_DEFAULT_CACHE_SIZE 3
+ //#define BTREE_LARGEST_ROOT_PAGE 4
+ //#define BTREE_TEXT_ENCODING 5
+ //#define BTREE_USER_VERSION 6
+ //#define BTREE_INCR_VACUUM 7
+ const int BTREE_FREE_PAGE_COUNT = 0;
+ const int BTREE_SCHEMA_VERSION = 1;
+ const int BTREE_FILE_FORMAT = 2;
+ const int BTREE_DEFAULT_CACHE_SIZE = 3;
+ const int BTREE_LARGEST_ROOT_PAGE = 4;
+ const int BTREE_TEXT_ENCODING = 5;
+ const int BTREE_USER_VERSION = 6;
+ const int BTREE_INCR_VACUUM = 7;
+
+ //int sqlite3BtreeCursor(
+ // Btree*, /* BTree containing table to open */
+ // int iTable, /* Index of root page */
+ // int wrFlag, /* 1 for writing. 0 for read-only */
+ // struct KeyInfo*, /* First argument to compare function */
+ // BtCursor pCursor /* Space to write cursor structure */
+ //);
+ //int sqlite3BtreeCursorSize(void);
+ //void sqlite3BtreeCursorZero(BtCursor);
+
+ //int sqlite3BtreeCloseCursor(BtCursor);
+ //int sqlite3BtreeMovetoUnpacked(
+ // BtCursor*,
+ // UnpackedRecord pUnKey,
+ // i64 intKey,
+ // int bias,
+ // int pRes
+ //);
+ //int sqlite3BtreeCursorHasMoved(BtCursor*, int);
+ //int sqlite3BtreeDelete(BtCursor);
+ //int sqlite3BtreeInsert(BtCursor*, const void pKey, i64 nKey,
+ // const void pData, int nData,
+ // int nZero, int bias, int seekResult);
+ //int sqlite3BtreeFirst(BtCursor*, int pRes);
+ //int sqlite3BtreeLast(BtCursor*, int pRes);
+ //int sqlite3BtreeNext(BtCursor*, int pRes);
+ //int sqlite3BtreeEof(BtCursor);
+ //int sqlite3BtreePrevious(BtCursor*, int pRes);
+ //int sqlite3BtreeKeySize(BtCursor*, i64 pSize);
+ //int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void);
+ //const void *sqlite3BtreeKeyFetch(BtCursor*, int pAmt);
+ //const void *sqlite3BtreeDataFetch(BtCursor*, int pAmt);
+ //int sqlite3BtreeDataSize(BtCursor*, u32 pSize);
+ //int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void);
+ //void sqlite3BtreeSetCachedRowid(BtCursor*, sqlite3_int64);
+ //sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor);
+
+ //char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int);
+ //struct Pager *sqlite3BtreePager(Btree);
+
+ //int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void);
+ //void sqlite3BtreeCacheOverflow(BtCursor );
+ //void sqlite3BtreeClearCursor(BtCursor );
+
+ //int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
+
+ //#if !NDEBUG
+ //int sqlite3BtreeCursorIsValid(BtCursor);
+ //#endif
+
+ //#if !SQLITE_OMIT_BTREECOUNT
+ //int sqlite3BtreeCount(BtCursor *, i64 );
+ //#endif
+
+ //#if SQLITE_TEST
+ //int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
+ //void sqlite3BtreeCursorList(Btree);
+ //#endif
#if !SQLITE_OMIT_WAL
//int sqlite3BtreeCheckpoint(Btree*, int, int *, int );
#endif
- /*
-** If we are not using shared cache, then there is no need to
-** use mutexes to access the BtShared structures. So make the
-** Enter and Leave procedures no-ops.
-*/
+ /*
+ ** If we are not using shared cache, then there is no need to
+ ** use mutexes to access the BtShared structures. So make the
+ ** Enter and Leave procedures no-ops.
+ */
#if !SQLITE_OMIT_SHARED_CACHE
//void sqlite3BtreeEnter(Btree);
//void sqlite3BtreeEnterAll(sqlite3);
#else
- //# define sqlite3BtreeEnter(X)
- static void sqlite3BtreeEnter( Btree bt )
- {
- }
- //# define sqlite3BtreeEnterAll(X)
- static void sqlite3BtreeEnterAll( sqlite3 p )
- {
- }
+ //# define sqlite3BtreeEnter(X)
+ static void sqlite3BtreeEnter(Btree bt) {
+ }
+ //# define sqlite3BtreeEnterAll(X)
+ static void sqlite3BtreeEnterAll(sqlite3 p) {
+ }
#endif
#if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
@@ -257,50 +253,42 @@ static void sqlite3BtreeEnterAll( sqlite3 p )
int sqlite3SchemaMutexHeld(sqlite3*,int,Schema);
#endif
#else
- //# define sqlite3BtreeSharable(X) 0
- static bool sqlite3BtreeSharable( Btree X )
- {
- return false;
- }
-
- //# define sqlite3BtreeLeave(X)
- static void sqlite3BtreeLeave( Btree X )
- {
- }
-
- //# define sqlite3BtreeEnterCursor(X)
- static void sqlite3BtreeEnterCursor( BtCursor X )
- {
- }
-
- //# define sqlite3BtreeLeaveCursor(X)
- static void sqlite3BtreeLeaveCursor( BtCursor X )
- {
- }
-
- //# define sqlite3BtreeLeaveAll(X)
- static void sqlite3BtreeLeaveAll( sqlite3 X )
- {
- }
-
- //# define sqlite3BtreeHoldsMutex(X) 1
- static bool sqlite3BtreeHoldsMutex( Btree X )
- {
- return true;
- }
-
- //# define sqlite3BtreeHoldsAllMutexes(X) 1
- static bool sqlite3BtreeHoldsAllMutexes( sqlite3 X )
- {
- return true;
- }
- //# define sqlite3SchemaMutexHeld(X,Y,Z) 1
- static bool sqlite3SchemaMutexHeld( sqlite3 X, int y, Schema z )
- {
- return true;
- }
+ //# define sqlite3BtreeSharable(X) 0
+ static bool sqlite3BtreeSharable(Btree X) {
+ return false;
+ }
+
+ //# define sqlite3BtreeLeave(X)
+ static void sqlite3BtreeLeave(Btree X) {
+ }
+
+ //# define sqlite3BtreeEnterCursor(X)
+ static void sqlite3BtreeEnterCursor(BtCursor X) {
+ }
+
+ //# define sqlite3BtreeLeaveCursor(X)
+ static void sqlite3BtreeLeaveCursor(BtCursor X) {
+ }
+
+ //# define sqlite3BtreeLeaveAll(X)
+ static void sqlite3BtreeLeaveAll(sqlite3 X) {
+ }
+
+ //# define sqlite3BtreeHoldsMutex(X) 1
+ static bool sqlite3BtreeHoldsMutex(Btree X) {
+ return true;
+ }
+
+ //# define sqlite3BtreeHoldsAllMutexes(X) 1
+ static bool sqlite3BtreeHoldsAllMutexes(sqlite3 X) {
+ return true;
+ }
+ //# define sqlite3SchemaMutexHeld(X,Y,Z) 1
+ static bool sqlite3SchemaMutexHeld(sqlite3 X, int y, Schema z) {
+ return true;
+ }
#endif
- //#endif // * _BTREE_H_ */
- }
+ //#endif // * _BTREE_H_ */
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/Delegates.cs b/Src/IronPython.SQLite/c#sqlite/Delegates.cs
index 97a7aeb4f..e59053ae5 100644
--- a/Src/IronPython.SQLite/c#sqlite/Delegates.cs
+++ b/Src/IronPython.SQLite/c#sqlite/Delegates.cs
@@ -7,103 +7,101 @@
using System;
using System.Text;
+
using HANDLE = System.IntPtr;
-using i16 = System.Int16;
using sqlite3_int64 = System.Int64;
using u32 = System.UInt32;
-namespace Community.CsharpSqlite
-{
- using DbPage = Sqlite3.PgHdr;
- using sqlite3_pcache = Sqlite3.PCache1;
- using sqlite3_stmt = Sqlite3.Vdbe;
- using sqlite3_value = Sqlite3.Mem;
+namespace Community.CsharpSqlite {
+ using DbPage = Sqlite3.PgHdr;
+ using sqlite3_pcache = Sqlite3.PCache1;
+ using sqlite3_stmt = Sqlite3.Vdbe;
+ using sqlite3_value = Sqlite3.Mem;
- public partial class Sqlite3
- {
- public delegate void dxAuth( object pAuthArg, int b, string c, string d, string e, string f );
- public delegate int dxBusy( object pBtShared, int iValue );
- public delegate void dxFreeAux( object pAuxArg );
- public delegate int dxCallback( object pCallbackArg, sqlite3_int64 argc, object p2, object p3 );
- public delegate void dxalarmCallback( object pNotUsed, sqlite3_int64 iNotUsed, int size );
- public delegate void dxCollNeeded( object pCollNeededArg, sqlite3 db, int eTextRep, string collationName );
- public delegate int dxCommitCallback( object pCommitArg );
- public delegate int dxCompare( object pCompareArg, int size1, string Key1, int size2, string Key2 );
- public delegate bool dxCompare4( string Key1, int size1, string Key2, int size2 );
- public delegate void dxDel( ref string pDelArg ); // needs ref
- public delegate void dxDelCollSeq( ref object pDelArg ); // needs ref
- public delegate void dxLog( object pLogArg, int i, string msg );
- public delegate void dxLogcallback( object pCallbackArg, int argc, string p2 );
- public delegate void dxProfile( object pProfileArg, string msg, sqlite3_int64 time );
- public delegate int dxProgress( object pProgressArg );
- public delegate void dxRollbackCallback( object pRollbackArg );
- public delegate void dxTrace( object pTraceArg, string msg );
- public delegate void dxUpdateCallback( object pUpdateArg, int b, string c, string d, sqlite3_int64 e );
- public delegate int dxWalCallback( object pWalArg, sqlite3 db, string zDb, int nEntry );
+ public partial class Sqlite3 {
+ public delegate void dxAuth(object pAuthArg, int b, string c, string d, string e, string f);
+ public delegate int dxBusy(object pBtShared, int iValue);
+ public delegate void dxFreeAux(object pAuxArg);
+ public delegate int dxCallback(object pCallbackArg, sqlite3_int64 argc, object p2, object p3);
+ public delegate void dxalarmCallback(object pNotUsed, sqlite3_int64 iNotUsed, int size);
+ public delegate void dxCollNeeded(object pCollNeededArg, sqlite3 db, int eTextRep, string collationName);
+ public delegate int dxCommitCallback(object pCommitArg);
+ public delegate int dxCompare(object pCompareArg, int size1, string Key1, int size2, string Key2);
+ public delegate bool dxCompare4(string Key1, int size1, string Key2, int size2);
+ public delegate void dxDel(ref string pDelArg); // needs ref
+ public delegate void dxDelCollSeq(ref object pDelArg); // needs ref
+ public delegate void dxLog(object pLogArg, int i, string msg);
+ public delegate void dxLogcallback(object pCallbackArg, int argc, string p2);
+ public delegate void dxProfile(object pProfileArg, string msg, sqlite3_int64 time);
+ public delegate int dxProgress(object pProgressArg);
+ public delegate void dxRollbackCallback(object pRollbackArg);
+ public delegate void dxTrace(object pTraceArg, string msg);
+ public delegate void dxUpdateCallback(object pUpdateArg, int b, string c, string d, sqlite3_int64 e);
+ public delegate int dxWalCallback(object pWalArg, sqlite3 db, string zDb, int nEntry);
- /*
- * FUNCTIONS
- *
- */
- public delegate void dxFunc( sqlite3_context ctx, int intValue, sqlite3_value[] value );
- public delegate void dxStep( sqlite3_context ctx, int intValue, sqlite3_value[] value );
- public delegate void dxFinal( sqlite3_context ctx );
- public delegate void dxFDestroy( object pArg );
- //
- public delegate string dxColname( sqlite3_value pVal );
- public delegate int dxFuncBtree( Btree p );
- public delegate int dxExprTreeFunction( ref int pArg, Expr pExpr );
- public delegate int dxExprTreeFunction_NC( NameContext pArg, ref Expr pExpr );
- public delegate int dxExprTreeFunction_OBJ( object pArg, Expr pExpr );
- /*
- VFS Delegates
- */
- public delegate int dxClose( sqlite3_file File_ID );
- public delegate int dxCheckReservedLock( sqlite3_file File_ID, ref int pRes );
- public delegate int dxDeviceCharacteristics( sqlite3_file File_ID );
- public delegate int dxFileControl( sqlite3_file File_ID, int op, ref sqlite3_int64 pArgs );
- public delegate int dxFileSize( sqlite3_file File_ID, ref long size );
- public delegate int dxLock( sqlite3_file File_ID, int locktype );
- public delegate int dxRead( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset );
- public delegate int dxSectorSize( sqlite3_file File_ID );
- public delegate int dxSync( sqlite3_file File_ID, int flags );
- public delegate int dxTruncate( sqlite3_file File_ID, sqlite3_int64 size );
- public delegate int dxUnlock( sqlite3_file File_ID, int locktype );
- public delegate int dxWrite( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset );
- public delegate int dxShmMap( sqlite3_file File_ID, int iPg, int pgsz, int pInt, out object pvolatile );
- public delegate int dxShmLock( sqlite3_file File_ID, int offset, int n, int flags );
- public delegate void dxShmBarrier( sqlite3_file File_ID );
- public delegate int dxShmUnmap( sqlite3_file File_ID, int deleteFlag );
- /*
- sqlite_vfs Delegates
- */
- public delegate int dxOpen( sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, out int pOutFlags );
- public delegate int dxDelete( sqlite3_vfs vfs, string zName, int syncDir );
- public delegate int dxAccess( sqlite3_vfs vfs, string zName, int flags, out int pResOut );
- public delegate int dxFullPathname( sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut );
- public delegate HANDLE dxDlOpen( sqlite3_vfs vfs, string zFilename );
- public delegate int dxDlError( sqlite3_vfs vfs, int nByte, string zErrMsg );
- public delegate HANDLE dxDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol );
- public delegate int dxDlClose( sqlite3_vfs vfs, HANDLE data );
- public delegate int dxRandomness( sqlite3_vfs vfs, int nByte, byte[] buffer );
- public delegate int dxSleep( sqlite3_vfs vfs, int microseconds );
- public delegate int dxCurrentTime( sqlite3_vfs vfs, ref double currenttime );
- public delegate int dxGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf );
- public delegate int dxCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTime );
- public delegate int dxSetSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr );
- public delegate int dxGetSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr );
- public delegate int dxNextSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr );
+ /*
+ * FUNCTIONS
+ *
+ */
+ public delegate void dxFunc(sqlite3_context ctx, int intValue, sqlite3_value[] value);
+ public delegate void dxStep(sqlite3_context ctx, int intValue, sqlite3_value[] value);
+ public delegate void dxFinal(sqlite3_context ctx);
+ public delegate void dxFDestroy(object pArg);
+ //
+ public delegate string dxColname(sqlite3_value pVal);
+ public delegate int dxFuncBtree(Btree p);
+ public delegate int dxExprTreeFunction(ref int pArg, Expr pExpr);
+ public delegate int dxExprTreeFunction_NC(NameContext pArg, ref Expr pExpr);
+ public delegate int dxExprTreeFunction_OBJ(object pArg, Expr pExpr);
+ /*
+ VFS Delegates
+ */
+ public delegate int dxClose(sqlite3_file File_ID);
+ public delegate int dxCheckReservedLock(sqlite3_file File_ID, ref int pRes);
+ public delegate int dxDeviceCharacteristics(sqlite3_file File_ID);
+ public delegate int dxFileControl(sqlite3_file File_ID, int op, ref sqlite3_int64 pArgs);
+ public delegate int dxFileSize(sqlite3_file File_ID, ref long size);
+ public delegate int dxLock(sqlite3_file File_ID, int locktype);
+ public delegate int dxRead(sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset);
+ public delegate int dxSectorSize(sqlite3_file File_ID);
+ public delegate int dxSync(sqlite3_file File_ID, int flags);
+ public delegate int dxTruncate(sqlite3_file File_ID, sqlite3_int64 size);
+ public delegate int dxUnlock(sqlite3_file File_ID, int locktype);
+ public delegate int dxWrite(sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset);
+ public delegate int dxShmMap(sqlite3_file File_ID, int iPg, int pgsz, int pInt, out object pvolatile);
+ public delegate int dxShmLock(sqlite3_file File_ID, int offset, int n, int flags);
+ public delegate void dxShmBarrier(sqlite3_file File_ID);
+ public delegate int dxShmUnmap(sqlite3_file File_ID, int deleteFlag);
+ /*
+ sqlite_vfs Delegates
+ */
+ public delegate int dxOpen(sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, out int pOutFlags);
+ public delegate int dxDelete(sqlite3_vfs vfs, string zName, int syncDir);
+ public delegate int dxAccess(sqlite3_vfs vfs, string zName, int flags, out int pResOut);
+ public delegate int dxFullPathname(sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut);
+ public delegate HANDLE dxDlOpen(sqlite3_vfs vfs, string zFilename);
+ public delegate int dxDlError(sqlite3_vfs vfs, int nByte, string zErrMsg);
+ public delegate HANDLE dxDlSym(sqlite3_vfs vfs, HANDLE data, string zSymbol);
+ public delegate int dxDlClose(sqlite3_vfs vfs, HANDLE data);
+ public delegate int dxRandomness(sqlite3_vfs vfs, int nByte, byte[] buffer);
+ public delegate int dxSleep(sqlite3_vfs vfs, int microseconds);
+ public delegate int dxCurrentTime(sqlite3_vfs vfs, ref double currenttime);
+ public delegate int dxGetLastError(sqlite3_vfs pVfs, int nBuf, ref string zBuf);
+ public delegate int dxCurrentTimeInt64(sqlite3_vfs pVfs, ref sqlite3_int64 pTime);
+ public delegate int dxSetSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr);
+ public delegate int dxGetSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr);
+ public delegate int dxNextSystemCall(sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr);
- /*
- * Pager Delegates
- */
+ /*
+ * Pager Delegates
+ */
- public delegate void dxDestructor( DbPage dbPage ); /* Call this routine when freeing pages */
- public delegate int dxBusyHandler( object pBusyHandlerArg );
- public delegate void dxReiniter( DbPage dbPage ); /* Call this routine when reloading pages */
+ public delegate void dxDestructor(DbPage dbPage); /* Call this routine when freeing pages */
+ public delegate int dxBusyHandler(object pBusyHandlerArg);
+ public delegate void dxReiniter(DbPage dbPage); /* Call this routine when reloading pages */
- public delegate void dxFreeSchema( Schema schema );
+ public delegate void dxFreeSchema(Schema schema);
#if SQLITE_HAS_CODEC
public delegate byte[] dxCodec( codec_ctx pCodec, byte[] D, uint pageNumber, int X ); //void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
@@ -111,184 +109,184 @@ sqlite_vfs Delegates
public delegate void dxCodecFree( ref codec_ctx pCodec ); //void (*xCodecFree)(void); /* Destructor for the codec */
#endif
- //Module
- public delegate void dxDestroy( ref PgHdr pDestroyArg );
- public delegate int dxStress( object obj, PgHdr pPhHdr );
+ //Module
+ public delegate void dxDestroy(ref PgHdr pDestroyArg);
+ public delegate int dxStress(object obj, PgHdr pPhHdr);
- //sqlite3_module
- public delegate int smdxCreateConnect( sqlite3 db, object pAux, int argc, string[] constargv, out sqlite3_vtab ppVTab, out string pError );
- public delegate int smdxBestIndex( sqlite3_vtab pVTab, ref sqlite3_index_info pIndex );
- public delegate int smdxDisconnect( ref object pVTab );
- public delegate int smdxDestroy(ref object pVTab );
- public delegate int smdxOpen( sqlite3_vtab pVTab, out sqlite3_vtab_cursor ppCursor );
- public delegate int smdxClose( ref sqlite3_vtab_cursor pCursor );
- public delegate int smdxFilter( sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv );
- public delegate int smdxNext( sqlite3_vtab_cursor pCursor );
- public delegate int smdxEof( sqlite3_vtab_cursor pCursor );
- public delegate int smdxColumn( sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3 );
- public delegate int smdxRowid( sqlite3_vtab_cursor pCursor, out sqlite3_int64 pRowid );
- public delegate int smdxUpdate( sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, out sqlite3_int64 p3 );
- public delegate int smdxFunction ( sqlite3_vtab pVTab );
- public delegate int smdxFindFunction( sqlite3_vtab pVtab, int nArg, string zName, ref dxFunc pxFunc, ref object ppArg );
- public delegate int smdxRename( sqlite3_vtab pVtab, string zNew );
- public delegate int smdxFunctionArg (sqlite3_vtab pVTab, int nArg );
+ //sqlite3_module
+ public delegate int smdxCreateConnect(sqlite3 db, object pAux, int argc, string[] constargv, out sqlite3_vtab ppVTab, out string pError);
+ public delegate int smdxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndex);
+ public delegate int smdxDisconnect(ref object pVTab);
+ public delegate int smdxDestroy(ref object pVTab);
+ public delegate int smdxOpen(sqlite3_vtab pVTab, out sqlite3_vtab_cursor ppCursor);
+ public delegate int smdxClose(ref sqlite3_vtab_cursor pCursor);
+ public delegate int smdxFilter(sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv);
+ public delegate int smdxNext(sqlite3_vtab_cursor pCursor);
+ public delegate int smdxEof(sqlite3_vtab_cursor pCursor);
+ public delegate int smdxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3);
+ public delegate int smdxRowid(sqlite3_vtab_cursor pCursor, out sqlite3_int64 pRowid);
+ public delegate int smdxUpdate(sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, out sqlite3_int64 p3);
+ public delegate int smdxFunction(sqlite3_vtab pVTab);
+ public delegate int smdxFindFunction(sqlite3_vtab pVtab, int nArg, string zName, ref dxFunc pxFunc, ref object ppArg);
+ public delegate int smdxRename(sqlite3_vtab pVtab, string zNew);
+ public delegate int smdxFunctionArg(sqlite3_vtab pVTab, int nArg);
- //AutoExtention
- public delegate int dxInit( sqlite3 db, ref string zMessage, sqlite3_api_routines sar );
+ //AutoExtention
+ public delegate int dxInit(sqlite3 db, ref string zMessage, sqlite3_api_routines sar);
#if !SQLITE_OMIT_VIRTUALTABLE
- public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
- public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
- public delegate int dmxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndexInfo);
- public delegate int dmxDisconnect(sqlite3_vtab pVTab);
- public delegate int dmxDestroy(sqlite3_vtab pVTab);
- public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor);
- public delegate int dmxClose(sqlite3_vtab_cursor pCursor);
- public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv);
- public delegate int dmxNext(sqlite3_vtab_cursor pCursor);
- public delegate int dmxEof(sqlite3_vtab_cursor pCursor);
- public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3);
- public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid);
- public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4);
- public delegate int dmxBegin(sqlite3_vtab pVTab);
- public delegate int dmxSync(sqlite3_vtab pVTab);
- public delegate int dmxCommit(sqlite3_vtab pVTab);
- public delegate int dmxRollback(sqlite3_vtab pVTab);
- public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName);
- public delegate int dmxRename(sqlite3_vtab pVtab, string zNew);
+ public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
+ public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
+ public delegate int dmxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndexInfo);
+ public delegate int dmxDisconnect(sqlite3_vtab pVTab);
+ public delegate int dmxDestroy(sqlite3_vtab pVTab);
+ public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor);
+ public delegate int dmxClose(sqlite3_vtab_cursor pCursor);
+ public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv);
+ public delegate int dmxNext(sqlite3_vtab_cursor pCursor);
+ public delegate int dmxEof(sqlite3_vtab_cursor pCursor);
+ public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3);
+ public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid);
+ public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4);
+ public delegate int dmxBegin(sqlite3_vtab pVTab);
+ public delegate int dmxSync(sqlite3_vtab pVTab);
+ public delegate int dmxCommit(sqlite3_vtab pVTab);
+ public delegate int dmxRollback(sqlite3_vtab pVTab);
+ public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName);
+ public delegate int dmxRename(sqlite3_vtab pVtab, string zNew);
#endif
- //Faults
- public delegate void void_function();
+ //Faults
+ public delegate void void_function();
- //Mem Methods
- public delegate int dxMemInit( object o );
- public delegate void dxMemShutdown( object o );
- public delegate byte[] dxMalloc( int nSize );
- public delegate int[] dxMallocInt( int nSize );
- public delegate Mem dxMallocMem( Mem pMem );
- public delegate void dxFree( ref byte[] pOld );
- public delegate void dxFreeInt( ref int[] pOld );
- public delegate void dxFreeMem( ref Mem pOld );
- public delegate byte[] dxRealloc( byte[] pOld, int nSize );
- public delegate int dxSize( byte[] pArray );
- public delegate int dxRoundup( int nSize );
+ //Mem Methods
+ public delegate int dxMemInit(object o);
+ public delegate void dxMemShutdown(object o);
+ public delegate byte[] dxMalloc(int nSize);
+ public delegate int[] dxMallocInt(int nSize);
+ public delegate Mem dxMallocMem(Mem pMem);
+ public delegate void dxFree(ref byte[] pOld);
+ public delegate void dxFreeInt(ref int[] pOld);
+ public delegate void dxFreeMem(ref Mem pOld);
+ public delegate byte[] dxRealloc(byte[] pOld, int nSize);
+ public delegate int dxSize(byte[] pArray);
+ public delegate int dxRoundup(int nSize);
- //Mutex Methods
- public delegate int dxMutexInit();
- public delegate int dxMutexEnd();
- public delegate sqlite3_mutex dxMutexAlloc( int iNumber );
- public delegate void dxMutexFree( sqlite3_mutex sm );
- public delegate void dxMutexEnter( sqlite3_mutex sm );
- public delegate int dxMutexTry( sqlite3_mutex sm );
- public delegate void dxMutexLeave( sqlite3_mutex sm );
- public delegate bool dxMutexHeld( sqlite3_mutex sm );
- public delegate bool dxMutexNotheld( sqlite3_mutex sm );
+ //Mutex Methods
+ public delegate int dxMutexInit();
+ public delegate int dxMutexEnd();
+ public delegate sqlite3_mutex dxMutexAlloc(int iNumber);
+ public delegate void dxMutexFree(sqlite3_mutex sm);
+ public delegate void dxMutexEnter(sqlite3_mutex sm);
+ public delegate int dxMutexTry(sqlite3_mutex sm);
+ public delegate void dxMutexLeave(sqlite3_mutex sm);
+ public delegate bool dxMutexHeld(sqlite3_mutex sm);
+ public delegate bool dxMutexNotheld(sqlite3_mutex sm);
- public delegate object dxColumn( sqlite3_stmt pStmt, int i );
- public delegate int dxColumn_I( sqlite3_stmt pStmt, int i );
+ public delegate object dxColumn(sqlite3_stmt pStmt, int i);
+ public delegate int dxColumn_I(sqlite3_stmt pStmt, int i);
- // Walker Methods
- public delegate int dxExprCallback( Walker W, ref Expr E ); /* Callback for expressions */
- public delegate int dxSelectCallback( Walker W, Select S ); /* Callback for SELECTs */
+ // Walker Methods
+ public delegate int dxExprCallback(Walker W, ref Expr E); /* Callback for expressions */
+ public delegate int dxSelectCallback(Walker W, Select S); /* Callback for SELECTs */
- // pcache Methods
- public delegate int dxPC_Init( object NotUsed );
- public delegate void dxPC_Shutdown( object NotUsed );
- public delegate sqlite3_pcache dxPC_Create( int szPage, bool bPurgeable );
- public delegate void dxPC_Cachesize( sqlite3_pcache pCache, int nCachesize );
- public delegate int dxPC_Pagecount( sqlite3_pcache pCache );
- public delegate PgHdr dxPC_Fetch( sqlite3_pcache pCache, u32 key, int createFlag );
- public delegate void dxPC_Unpin( sqlite3_pcache pCache, PgHdr p2, bool discard );
- public delegate void dxPC_Rekey( sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey );
- public delegate void dxPC_Truncate( sqlite3_pcache pCache, u32 iLimit );
- public delegate void dxPC_Destroy( ref sqlite3_pcache pCache );
+ // pcache Methods
+ public delegate int dxPC_Init(object NotUsed);
+ public delegate void dxPC_Shutdown(object NotUsed);
+ public delegate sqlite3_pcache dxPC_Create(int szPage, bool bPurgeable);
+ public delegate void dxPC_Cachesize(sqlite3_pcache pCache, int nCachesize);
+ public delegate int dxPC_Pagecount(sqlite3_pcache pCache);
+ public delegate PgHdr dxPC_Fetch(sqlite3_pcache pCache, u32 key, int createFlag);
+ public delegate void dxPC_Unpin(sqlite3_pcache pCache, PgHdr p2, bool discard);
+ public delegate void dxPC_Rekey(sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey);
+ public delegate void dxPC_Truncate(sqlite3_pcache pCache, u32 iLimit);
+ public delegate void dxPC_Destroy(ref sqlite3_pcache pCache);
- public delegate void dxIter( PgHdr p );
+ public delegate void dxIter(PgHdr p);
#if NET_35 || NET_40
- //API Simplifications -- Actions
- public static Action ResultBlob = sqlite3_result_blob;
- public static Action ResultDouble = sqlite3_result_double;
- public static Action ResultError = sqlite3_result_error;
- public static Action ResultErrorCode = sqlite3_result_error_code;
- public static Action ResultErrorNoMem = sqlite3_result_error_nomem;
- public static Action ResultErrorTooBig = sqlite3_result_error_toobig;
- public static Action ResultInt = sqlite3_result_int;
- public static Action ResultInt64 = sqlite3_result_int64;
- public static Action ResultNull = sqlite3_result_null;
- public static Action ResultText = sqlite3_result_text;
- public static Action ResultText_Offset = sqlite3_result_text;
- public static Action ResultValue = sqlite3_result_value;
- public static Action ResultZeroblob = sqlite3_result_zeroblob;
- public static Action SetAuxdata = sqlite3_set_auxdata;
+ //API Simplifications -- Actions
+ public static Action ResultBlob = sqlite3_result_blob;
+ public static Action ResultDouble = sqlite3_result_double;
+ public static Action ResultError = sqlite3_result_error;
+ public static Action ResultErrorCode = sqlite3_result_error_code;
+ public static Action ResultErrorNoMem = sqlite3_result_error_nomem;
+ public static Action ResultErrorTooBig = sqlite3_result_error_toobig;
+ public static Action ResultInt = sqlite3_result_int;
+ public static Action ResultInt64 = sqlite3_result_int64;
+ public static Action ResultNull = sqlite3_result_null;
+ public static Action ResultText = sqlite3_result_text;
+ public static Action ResultText_Offset = sqlite3_result_text;
+ public static Action ResultValue = sqlite3_result_value;
+ public static Action ResultZeroblob = sqlite3_result_zeroblob;
+ public static Action SetAuxdata = sqlite3_set_auxdata;
- //API Simplifications -- Functions
- public delegate Int32 FinalizeDelegate( sqlite3_stmt pStmt );
- public static FinalizeDelegate Finalize = sqlite3_finalize;
+ //API Simplifications -- Functions
+ public delegate Int32 FinalizeDelegate(sqlite3_stmt pStmt);
+ public static FinalizeDelegate Finalize = sqlite3_finalize;
- public static Func ClearBindings = sqlite3_clear_bindings;
- public static Func ColumnBlob = sqlite3_column_blob;
- public static Func ColumnBytes = sqlite3_column_bytes;
- public static Func ColumnBytes16 = sqlite3_column_bytes16;
- public static Func ColumnCount = sqlite3_column_count;
- public static Func ColumnDecltype = sqlite3_column_decltype;
- public static Func ColumnDouble = sqlite3_column_double;
- public static Func ColumnInt = sqlite3_column_int;
- public static Func ColumnInt64 = sqlite3_column_int64;
- public static Func ColumnName = sqlite3_column_name;
- public static Func ColumnText = sqlite3_column_text;
- public static Func ColumnType = sqlite3_column_type;
- public static Func ColumnValue = sqlite3_column_value;
- public static Func DataCount = sqlite3_data_count;
- public static Func Reset = sqlite3_reset;
- public static Func Step = sqlite3_step;
+ public static Func ClearBindings = sqlite3_clear_bindings;
+ public static Func ColumnBlob = sqlite3_column_blob;
+ public static Func ColumnBytes = sqlite3_column_bytes;
+ public static Func ColumnBytes16 = sqlite3_column_bytes16;
+ public static Func ColumnCount = sqlite3_column_count;
+ public static Func ColumnDecltype = sqlite3_column_decltype;
+ public static Func ColumnDouble = sqlite3_column_double;
+ public static Func ColumnInt = sqlite3_column_int;
+ public static Func ColumnInt64 = sqlite3_column_int64;
+ public static Func ColumnName = sqlite3_column_name;
+ public static Func ColumnText = sqlite3_column_text;
+ public static Func ColumnType = sqlite3_column_type;
+ public static Func ColumnValue = sqlite3_column_value;
+ public static Func DataCount = sqlite3_data_count;
+ public static Func Reset = sqlite3_reset;
+ public static Func Step = sqlite3_step;
- public static Func BindBlob = sqlite3_bind_blob;
- public static Func BindDouble = sqlite3_bind_double;
- public static Func BindInt = sqlite3_bind_int;
- public static Func BindInt64 = sqlite3_bind_int64;
- public static Func BindNull = sqlite3_bind_null;
- public static Func BindParameterCount = sqlite3_bind_parameter_count;
- public static Func BindParameterIndex = sqlite3_bind_parameter_index;
- public static Func BindParameterName = sqlite3_bind_parameter_name;
- public static Func BindText = sqlite3_bind_text;
- public static Func BindValue = sqlite3_bind_value;
- public static Func BindZeroblob = sqlite3_bind_zeroblob;
+ public static Func BindBlob = sqlite3_bind_blob;
+ public static Func BindDouble = sqlite3_bind_double;
+ public static Func BindInt = sqlite3_bind_int;
+ public static Func BindInt64 = sqlite3_bind_int64;
+ public static Func BindNull = sqlite3_bind_null;
+ public static Func BindParameterCount = sqlite3_bind_parameter_count;
+ public static Func BindParameterIndex = sqlite3_bind_parameter_index;
+ public static Func BindParameterName = sqlite3_bind_parameter_name;
+ public static Func BindText = sqlite3_bind_text;
+ public static Func BindValue = sqlite3_bind_value;
+ public static Func BindZeroblob = sqlite3_bind_zeroblob;
- public delegate Int32 OpenDelegate( string zFilename, out sqlite3 ppDb );
- public static Func Close = sqlite3_close;
- public static Func DbHandle = sqlite3_db_handle;
- public static Func Errmsg = sqlite3_errmsg;
- public static OpenDelegate Open = sqlite3_open;
- public static Func NextStmt = sqlite3_next_stmt;
- public static Func Shutdown = sqlite3_shutdown;
- public static Func StmtStatus = sqlite3_stmt_status;
+ public delegate Int32 OpenDelegate(string zFilename, out sqlite3 ppDb);
+ public static Func Close = sqlite3_close;
+ public static Func DbHandle = sqlite3_db_handle;
+ public static Func Errmsg = sqlite3_errmsg;
+ public static OpenDelegate Open = sqlite3_open;
+ public static Func NextStmt = sqlite3_next_stmt;
+ public static Func Shutdown = sqlite3_shutdown;
+ public static Func StmtStatus = sqlite3_stmt_status;
- public delegate Int32 PrepareDelegate( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, ref string pzTail );
- public delegate Int32 PrepareDelegateNoTail( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, Int32 iDummy );
- public static PrepareDelegate Prepare = sqlite3_prepare;
- public static PrepareDelegate PrepareV2 = sqlite3_prepare_v2;
- public static PrepareDelegateNoTail PrepareV2NoTail = sqlite3_prepare_v2;
+ public delegate Int32 PrepareDelegate(sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, ref string pzTail);
+ public delegate Int32 PrepareDelegateNoTail(sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, Int32 iDummy);
+ public static PrepareDelegate Prepare = sqlite3_prepare;
+ public static PrepareDelegate PrepareV2 = sqlite3_prepare_v2;
+ public static PrepareDelegateNoTail PrepareV2NoTail = sqlite3_prepare_v2;
- public static Func AggregateContext = sqlite3_aggregate_context;
- public static Func GetAuxdata = sqlite3_get_auxdata;
- public static Func ContextDbHandle = sqlite3_context_db_handle;
- public static Func UserData = sqlite3_user_data;
+ public static Func AggregateContext = sqlite3_aggregate_context;
+ public static Func GetAuxdata = sqlite3_get_auxdata;
+ public static Func ContextDbHandle = sqlite3_context_db_handle;
+ public static Func UserData = sqlite3_user_data;
- public static Func ValueBlob = sqlite3_value_blob;
- public static Func ValueBytes = sqlite3_value_bytes;
- public static Func ValueBytes16 = sqlite3_value_bytes16;
- public static Func ValueDouble = sqlite3_value_double;
- public static Func ValueInt = sqlite3_value_int;
- public static Func ValueInt64 = sqlite3_value_int64;
- public static Func ValueText = sqlite3_value_text;
- public static Func ValueType = sqlite3_value_type;
+ public static Func ValueBlob = sqlite3_value_blob;
+ public static Func ValueBytes = sqlite3_value_bytes;
+ public static Func ValueBytes16 = sqlite3_value_bytes16;
+ public static Func ValueDouble = sqlite3_value_double;
+ public static Func ValueInt = sqlite3_value_int;
+ public static Func ValueInt64 = sqlite3_value_int64;
+ public static Func ValueText = sqlite3_value_text;
+ public static Func ValueType = sqlite3_value_type;
#endif
- }
+ }
}
-#if( NET_35 && !NET_40) || WINDOWS_PHONE
+#if (NET_35 && !NET_40) || WINDOWS_PHONE
namespace System
{
// Summary:
diff --git a/Src/IronPython.SQLite/c#sqlite/Hash_h.cs b/Src/IronPython.SQLite/c#sqlite/Hash_h.cs
index cbb09ce7a..7274cd967 100644
--- a/Src/IronPython.SQLite/c#sqlite/Hash_h.cs
+++ b/Src/IronPython.SQLite/c#sqlite/Hash_h.cs
@@ -1,141 +1,130 @@
-using u8 = System.Byte;
using u32 = System.UInt32;
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2001 September 22
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This is the header file for the generic hash-table implemenation
- ** used in SQLite.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
- **
- *************************************************************************
- */
- //#if !_SQLITE_HASH_H_
- //#define _SQLITE_HASH_H_
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 22
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This is the header file for the generic hash-table implemenation
+ ** used in SQLite.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
+ **
+ *************************************************************************
+ */
+ //#if !_SQLITE_HASH_H_
+ //#define _SQLITE_HASH_H_
- /* Forward declarations of structures. */
- //typedef struct Hash Hash;
- //typedef struct HashElem HashElem;
+ /* Forward declarations of structures. */
+ //typedef struct Hash Hash;
+ //typedef struct HashElem HashElem;
- /* A complete hash table is an instance of the following structure.
- ** The internals of this structure are intended to be opaque -- client
- ** code should not attempt to access or modify the fields of this structure
- ** directly. Change this structure only by using the routines below.
- ** However, some of the "procedures" and "functions" for modifying and
- ** accessing this structure are really macros, so we can't really make
- ** this structure opaque.
- **
- ** All elements of the hash table are on a single doubly-linked list.
- ** Hash.first points to the head of this list.
- **
- ** There are Hash.htsize buckets. Each bucket points to a spot in
- ** the global doubly-linked list. The contents of the bucket are the
- ** element pointed to plus the next _ht.count-1 elements in the list.
- **
- ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
- ** by a linear search of the global list. For small tables, the
- ** Hash.ht table is never allocated because if there are few elements
- ** in the table, it is faster to do a linear search than to manage
- ** the hash table.
- */
- public class _ht
- { /* the hash table */
- public int count; /* Number of entries with this hash */
- public HashElem chain; /* Pointer to first entry with this hash */
- };
+ /* A complete hash table is an instance of the following structure.
+ ** The internals of this structure are intended to be opaque -- client
+ ** code should not attempt to access or modify the fields of this structure
+ ** directly. Change this structure only by using the routines below.
+ ** However, some of the "procedures" and "functions" for modifying and
+ ** accessing this structure are really macros, so we can't really make
+ ** this structure opaque.
+ **
+ ** All elements of the hash table are on a single doubly-linked list.
+ ** Hash.first points to the head of this list.
+ **
+ ** There are Hash.htsize buckets. Each bucket points to a spot in
+ ** the global doubly-linked list. The contents of the bucket are the
+ ** element pointed to plus the next _ht.count-1 elements in the list.
+ **
+ ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
+ ** by a linear search of the global list. For small tables, the
+ ** Hash.ht table is never allocated because if there are few elements
+ ** in the table, it is faster to do a linear search than to manage
+ ** the hash table.
+ */
+ public class _ht { /* the hash table */
+ public int count; /* Number of entries with this hash */
+ public HashElem chain; /* Pointer to first entry with this hash */
+ };
- public class Hash
- {
- public u32 htsize = 31; /* Number of buckets in the hash table */
- public u32 count; /* Number of entries in this table */
- public HashElem first; /* The first element of the array */
- public _ht[] ht;
- public Hash Copy()
- {
- if ( this == null )
- return null;
- else
- {
- Hash cp = (Hash)MemberwiseClone();
- return cp;
- }
- }
- };
+ public class Hash {
+ public u32 htsize = 31; /* Number of buckets in the hash table */
+ public u32 count; /* Number of entries in this table */
+ public HashElem first; /* The first element of the array */
+ public _ht[] ht;
+ public Hash Copy() {
+ if (this == null)
+ return null;
+ else {
+ Hash cp = (Hash)MemberwiseClone();
+ return cp;
+ }
+ }
+ };
- /* Each element in the hash table is an instance of the following
- ** structure. All elements are stored on a single doubly-linked list.
- **
- ** Again, this structure is intended to be opaque, but it can't really
- ** be opaque because it is used by macros.
- */
- public class HashElem
- {
- public HashElem next;
- public HashElem prev; /* Next and previous elements in the table */
- public object data; /* Data associated with this element */
- public string pKey;
- public int nKey; /* Key associated with this element */
- };
+ /* Each element in the hash table is an instance of the following
+ ** structure. All elements are stored on a single doubly-linked list.
+ **
+ ** Again, this structure is intended to be opaque, but it can't really
+ ** be opaque because it is used by macros.
+ */
+ public class HashElem {
+ public HashElem next;
+ public HashElem prev; /* Next and previous elements in the table */
+ public object data; /* Data associated with this element */
+ public string pKey;
+ public int nKey; /* Key associated with this element */
+ };
- /*
- ** Access routines. To delete, insert a NULL pointer.
- */
- //void sqlite3HashInit(Hash);
- //void *sqlite3HashInsert(Hash*, string pKey, int nKey, object *pData);
- //void *sqlite3HashFind(const Hash*, string pKey, int nKey);
- //void sqlite3HashClear(Hash);
+ /*
+ ** Access routines. To delete, insert a NULL pointer.
+ */
+ //void sqlite3HashInit(Hash);
+ //void *sqlite3HashInsert(Hash*, string pKey, int nKey, object *pData);
+ //void *sqlite3HashFind(const Hash*, string pKey, int nKey);
+ //void sqlite3HashClear(Hash);
- /*
- ** Macros for looping over all elements of a hash table. The idiom is
- ** like this:
- **
- ** Hash h;
- ** HashElem p;
- ** ...
- ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
- ** SomeStructure pData = sqliteHashData(p);
- ** // do something with pData
- ** }
- */
- //#define sqliteHashFirst(H) ((H).first)
- static HashElem sqliteHashFirst( Hash H )
- {
- return H.first;
- }
- //#define sqliteHashNext(E) ((E).next)
- static HashElem sqliteHashNext( HashElem E )
- {
- return E.next;
- }
- //#define sqliteHashData(E) ((E).data)
- static object sqliteHashData( HashElem E )
- {
- return E.data;
- }
- /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
- /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
+ /*
+ ** Macros for looping over all elements of a hash table. The idiom is
+ ** like this:
+ **
+ ** Hash h;
+ ** HashElem p;
+ ** ...
+ ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
+ ** SomeStructure pData = sqliteHashData(p);
+ ** // do something with pData
+ ** }
+ */
+ //#define sqliteHashFirst(H) ((H).first)
+ static HashElem sqliteHashFirst(Hash H) {
+ return H.first;
+ }
+ //#define sqliteHashNext(E) ((E).next)
+ static HashElem sqliteHashNext(HashElem E) {
+ return E.next;
+ }
+ //#define sqliteHashData(E) ((E).data)
+ static object sqliteHashData(HashElem E) {
+ return E.data;
+ }
+ /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
+ /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
- /*
- ** Number of entries in a hash table
- */
- /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
+ /*
+ ** Number of entries in a hash table
+ */
+ /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
- //#endif // * _SQLITE_HASH_H_ */
- }
+ //#endif // * _SQLITE_HASH_H_ */
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/VdbeInt_h.cs b/Src/IronPython.SQLite/c#sqlite/VdbeInt_h.cs
index 8dba30007..2666c677b 100644
--- a/Src/IronPython.SQLite/c#sqlite/VdbeInt_h.cs
+++ b/Src/IronPython.SQLite/c#sqlite/VdbeInt_h.cs
@@ -1,6 +1,4 @@
using System;
-using System.Diagnostics;
-using System.Runtime.InteropServices;
using FILE = System.IO.TextWriter;
@@ -8,8 +6,6 @@
using u8 = System.Byte;
using u16 = System.UInt16;
using u32 = System.UInt32;
-using u64 = System.UInt64;
-using unsigned = System.UIntPtr;
using Pgno = System.UInt32;
@@ -30,176 +26,169 @@
#endif
-namespace Community.CsharpSqlite
-{
- using Op = Sqlite3.VdbeOp;
-
- public partial class Sqlite3
- {
- /*
- ** 2003 September 6
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This is the header file for information that is private to the
- ** VDBE. This information used to all be at the top of the single
- ** source code file "vdbe.c". When that file became too big (over
- ** 6000 lines long) it was split up into several smaller files and
- ** this header information was factored out.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#if !_VDBEINT_H_
- //#define _VDBEINT_H_
-
- /*
- ** SQL is translated into a sequence of instructions to be
- ** executed by a virtual machine. Each instruction is an instance
- ** of the following structure.
- */
- //typedef struct VdbeOp Op;
-
- /*
- ** Boolean values
- */
- //typedef unsigned char Bool;
-
- /*
- ** A cursor is a pointer into a single BTree within a database file.
- ** The cursor can seek to a BTree entry with a particular key, or
- ** loop over all entries of the Btree. You can also insert new BTree
- ** entries or retrieve the key or data from the entry that the cursor
- ** is currently pointing to.
- **
- ** Every cursor that the virtual machine has open is represented by an
- ** instance of the following structure.
- */
- public class VdbeCursor
- {
- public BtCursor pCursor; /* The cursor structure of the backend */
- public Btree pBt; /* Separate file holding temporary table */
- public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */
- public int iDb; /* Index of cursor database in db->aDb[] (or -1) */
- public int pseudoTableReg; /* Register holding pseudotable content. */
- public int nField; /* Number of fields in the header */
- public bool zeroed; /* True if zeroed out and ready for reuse */
- public bool rowidIsValid; /* True if lastRowid is valid */
- public bool atFirst; /* True if pointing to first entry */
- public bool useRandomRowid; /* Generate new record numbers semi-randomly */
- public bool nullRow; /* True if pointing to a row with no data */
- public bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
- public bool isTable; /* True if a table requiring integer keys */
- public bool isIndex; /* True if an index containing keys only - no data */
- public bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
+namespace Community.CsharpSqlite {
+ using Op = Sqlite3.VdbeOp;
+
+ public partial class Sqlite3 {
+ /*
+ ** 2003 September 6
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This is the header file for information that is private to the
+ ** VDBE. This information used to all be at the top of the single
+ ** source code file "vdbe.c". When that file became too big (over
+ ** 6000 lines long) it was split up into several smaller files and
+ ** this header information was factored out.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#if !_VDBEINT_H_
+ //#define _VDBEINT_H_
+
+ /*
+ ** SQL is translated into a sequence of instructions to be
+ ** executed by a virtual machine. Each instruction is an instance
+ ** of the following structure.
+ */
+ //typedef struct VdbeOp Op;
+
+ /*
+ ** Boolean values
+ */
+ //typedef unsigned char Bool;
+
+ /*
+ ** A cursor is a pointer into a single BTree within a database file.
+ ** The cursor can seek to a BTree entry with a particular key, or
+ ** loop over all entries of the Btree. You can also insert new BTree
+ ** entries or retrieve the key or data from the entry that the cursor
+ ** is currently pointing to.
+ **
+ ** Every cursor that the virtual machine has open is represented by an
+ ** instance of the following structure.
+ */
+ public class VdbeCursor {
+ public BtCursor pCursor; /* The cursor structure of the backend */
+ public Btree pBt; /* Separate file holding temporary table */
+ public KeyInfo pKeyInfo; /* Info about index keys needed by index cursors */
+ public int iDb; /* Index of cursor database in db->aDb[] (or -1) */
+ public int pseudoTableReg; /* Register holding pseudotable content. */
+ public int nField; /* Number of fields in the header */
+ public bool zeroed; /* True if zeroed out and ready for reuse */
+ public bool rowidIsValid; /* True if lastRowid is valid */
+ public bool atFirst; /* True if pointing to first entry */
+ public bool useRandomRowid; /* Generate new record numbers semi-randomly */
+ public bool nullRow; /* True if pointing to a row with no data */
+ public bool deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
+ public bool isTable; /* True if a table requiring integer keys */
+ public bool isIndex; /* True if an index containing keys only - no data */
+ public bool isOrdered; /* True if the underlying table is BTREE_UNORDERED */
#if !SQLITE_OMIT_VIRTUALTABLE
- public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */
- public sqlite3_module pModule; /* Module for cursor pVtabCursor */
+ public sqlite3_vtab_cursor pVtabCursor; /* The cursor for a virtual table */
+ public sqlite3_module pModule; /* Module for cursor pVtabCursor */
#endif
- public i64 seqCount; /* Sequence counter */
- public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
- public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
-
- /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
- ** OP_IsUnique opcode on this cursor. */
- public int seekResult;
-
- /* Cached information about the header for the data record that the
- ** cursor is currently pointing to. Only valid if cacheStatus matches
- ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
- ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
- ** the cache is out of date.
- **
- ** aRow might point to (ephemeral) data for the current row, or it might
- ** be NULL.
- */
- public u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
- public Pgno payloadSize; /* Total number of bytes in the record */
- public u32[] aType; /* Type values for all entries in the record */
- public u32[] aOffset; /* Cached offsets to the start of each columns data */
- public int aRow; /* Pointer to Data for the current row, if all on one page */
-
- public VdbeCursor Copy()
- {
- return (VdbeCursor)MemberwiseClone();
- }
- };
- //typedef struct VdbeCursor VdbeCursor;
-
-
- /*
- ** When a sub-program is executed (OP_Program), a structure of this type
- ** is allocated to store the current value of the program counter, as
- ** well as the current memory cell array and various other frame specific
- ** values stored in the Vdbe struct. When the sub-program is finished,
- ** these values are copied back to the Vdbe from the VdbeFrame structure,
- ** restoring the state of the VM to as it was before the sub-program
- ** began executing.
- **
- ** The memory for a VdbeFrame object is allocated and managed by a memory
- ** cell in the parent (calling) frame. When the memory cell is deleted or
- ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
- ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
- ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
- ** this instead of deleting the VdbeFrame immediately is to avoid recursive
- ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
- ** child frame are released.
- **
- ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
- ** set to NULL if the currently executing frame is the main program.
- */
- //typedef struct VdbeFrame VdbeFrame;
- public class VdbeFrame
- {
- public Vdbe v; /* VM this frame belongs to */
- public int pc; /* Program Counter in parent (calling) frame */
- public Op[] aOp; /* Program instructions for parent frame */
- public int nOp; /* Size of aOp array */
- public Mem[] aMem; /* Array of memory cells for parent frame */
- public int nMem; /* Number of entries in aMem */
- public VdbeCursor[] apCsr; /* Array of Vdbe cursors for parent frame */
- public u16 nCursor; /* Number of entries in apCsr */
- public int token; /* Copy of SubProgram.token */
- public int nChildMem; /* Number of memory cells for child frame */
- public int nChildCsr; /* Number of cursors for child frame */
- public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
- public int nChange; /* Statement changes (Vdbe.nChanges) */
- public VdbeFrame pParent; /* Parent of this frame, or NULL if parent is main */
- //
- // Needed for C# Implementation
- //
- public Mem[] aChildMem; /* Array of memory cells for child frame */
- public VdbeCursor[] aChildCsr; /* Array of cursors for child frame */
- };
-
- //#define VdbeFrameMem(p) ((Mem )&((u8 )p)[ROUND8(sizeof(VdbeFrame))])
- /*
- ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
- */
- const int CACHE_STALE = 0;
-
- /*
- ** Internally, the vdbe manipulates nearly all SQL values as Mem
- ** structures. Each Mem struct may cache multiple representations (string,
- ** integer etc.) of the same value.
- */
- public class Mem
- {
- public sqlite3 db; /* The associated database connection */
- public string z; /* String value */
- public double r; /* Real value */
- public struct union_ip
- {
+ public i64 seqCount; /* Sequence counter */
+ public i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
+ public i64 lastRowid; /* Last rowid from a Next or NextIdx operation */
+
+ /* Result of last sqlite3BtreeMoveto() done by an OP_NotExists or
+ ** OP_IsUnique opcode on this cursor. */
+ public int seekResult;
+
+ /* Cached information about the header for the data record that the
+ ** cursor is currently pointing to. Only valid if cacheStatus matches
+ ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
+ ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
+ ** the cache is out of date.
+ **
+ ** aRow might point to (ephemeral) data for the current row, or it might
+ ** be NULL.
+ */
+ public u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
+ public Pgno payloadSize; /* Total number of bytes in the record */
+ public u32[] aType; /* Type values for all entries in the record */
+ public u32[] aOffset; /* Cached offsets to the start of each columns data */
+ public int aRow; /* Pointer to Data for the current row, if all on one page */
+
+ public VdbeCursor Copy() {
+ return (VdbeCursor)MemberwiseClone();
+ }
+ };
+ //typedef struct VdbeCursor VdbeCursor;
+
+
+ /*
+ ** When a sub-program is executed (OP_Program), a structure of this type
+ ** is allocated to store the current value of the program counter, as
+ ** well as the current memory cell array and various other frame specific
+ ** values stored in the Vdbe struct. When the sub-program is finished,
+ ** these values are copied back to the Vdbe from the VdbeFrame structure,
+ ** restoring the state of the VM to as it was before the sub-program
+ ** began executing.
+ **
+ ** The memory for a VdbeFrame object is allocated and managed by a memory
+ ** cell in the parent (calling) frame. When the memory cell is deleted or
+ ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
+ ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
+ ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
+ ** this instead of deleting the VdbeFrame immediately is to avoid recursive
+ ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
+ ** child frame are released.
+ **
+ ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
+ ** set to NULL if the currently executing frame is the main program.
+ */
+ //typedef struct VdbeFrame VdbeFrame;
+ public class VdbeFrame {
+ public Vdbe v; /* VM this frame belongs to */
+ public int pc; /* Program Counter in parent (calling) frame */
+ public Op[] aOp; /* Program instructions for parent frame */
+ public int nOp; /* Size of aOp array */
+ public Mem[] aMem; /* Array of memory cells for parent frame */
+ public int nMem; /* Number of entries in aMem */
+ public VdbeCursor[] apCsr; /* Array of Vdbe cursors for parent frame */
+ public u16 nCursor; /* Number of entries in apCsr */
+ public int token; /* Copy of SubProgram.token */
+ public int nChildMem; /* Number of memory cells for child frame */
+ public int nChildCsr; /* Number of cursors for child frame */
+ public i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
+ public int nChange; /* Statement changes (Vdbe.nChanges) */
+ public VdbeFrame pParent; /* Parent of this frame, or NULL if parent is main */
+ //
+ // Needed for C# Implementation
+ //
+ public Mem[] aChildMem; /* Array of memory cells for child frame */
+ public VdbeCursor[] aChildCsr; /* Array of cursors for child frame */
+ };
+
+ //#define VdbeFrameMem(p) ((Mem )&((u8 )p)[ROUND8(sizeof(VdbeFrame))])
+ /*
+ ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
+ */
+ const int CACHE_STALE = 0;
+
+ /*
+ ** Internally, the vdbe manipulates nearly all SQL values as Mem
+ ** structures. Each Mem struct may cache multiple representations (string,
+ ** integer etc.) of the same value.
+ */
+ public class Mem {
+ public sqlite3 db; /* The associated database connection */
+ public string z; /* String value */
+ public double r; /* Real value */
+ public struct union_ip {
#if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL
public i64 _i; /* First operand */
public i64 i
@@ -208,16 +197,16 @@ public i64 i
set { _i = value; }
}
#else
- public i64 i; /* Integer value used when MEM_Int is set in flags */
+ public i64 i; /* Integer value used when MEM_Int is set in flags */
#endif
- public int nZero; /* Used when bit MEM_Zero is set in flags */
- public FuncDef pDef; /* Used only when flags==MEM_Agg */
- public RowSet pRowSet; /* Used only when flags==MEM_RowSet */
- public VdbeFrame pFrame; /* Used when flags==MEM_Frame */
- };
- public union_ip u;
- public byte[] zBLOB; /* BLOB value */
- public int n; /* Number of characters in string value, excluding '\0' */
+ public int nZero; /* Used when bit MEM_Zero is set in flags */
+ public FuncDef pDef; /* Used only when flags==MEM_Agg */
+ public RowSet pRowSet; /* Used only when flags==MEM_RowSet */
+ public VdbeFrame pFrame; /* Used when flags==MEM_Frame */
+ };
+ public union_ip u;
+ public byte[] zBLOB; /* BLOB value */
+ public int n; /* Number of characters in string value, excluding '\0' */
#if DEBUG_CLASS_MEM || DEBUG_CLASS_ALL
public u16 _flags; /* First operand */
public u16 flags
@@ -226,334 +215,322 @@ public u16 flags
set { _flags = value; }
}
#else
- public u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
+ public u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
#endif
- public u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
- public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
+ public u8 type; /* One of SQLITE_NULL, SQLITE_TEXT, SQLITE_INTEGER, etc */
+ public u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
#if SQLITE_DEBUG
- public Mem pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
- public object pFiller; /* So that sizeof(Mem) is a multiple of 8 */
+ public Mem pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
+ public object pFiller; /* So that sizeof(Mem) is a multiple of 8 */
#endif
- public dxDel xDel; /* If not null, call this function to delete Mem.z */
- // Not used under c#
- //public string zMalloc; /* Dynamic buffer allocated by sqlite3Malloc() */
- public Mem _Mem; /* Used when C# overload Z as MEM space */
- public SumCtx _SumCtx; /* Used when C# overload Z as Sum context */
- public SubProgram[] _SubProgram;/* Used when C# overload Z as SubProgram*/
- public StrAccum _StrAccum; /* Used when C# overload Z as STR context */
- public object _MD5Context; /* Used when C# overload Z as MD5 context */
-
- public Mem()
- {
- }
-
- public Mem( sqlite3 db, string z, double r, int i, int n, u16 flags, u8 type, u8 enc
+ public dxDel xDel; /* If not null, call this function to delete Mem.z */
+ // Not used under c#
+ //public string zMalloc; /* Dynamic buffer allocated by sqlite3Malloc() */
+ public Mem _Mem; /* Used when C# overload Z as MEM space */
+ public SumCtx _SumCtx; /* Used when C# overload Z as Sum context */
+ public SubProgram[] _SubProgram;/* Used when C# overload Z as SubProgram*/
+ public StrAccum _StrAccum; /* Used when C# overload Z as STR context */
+ public object _MD5Context; /* Used when C# overload Z as MD5 context */
+
+ public Mem() {
+ }
+
+ public Mem(sqlite3 db, string z, double r, int i, int n, u16 flags, u8 type, u8 enc
#if SQLITE_DEBUG
- , Mem pScopyFrom, object pFiller /* pScopyFrom, pFiller */
+ , Mem pScopyFrom, object pFiller /* pScopyFrom, pFiller */
#endif
- )
- {
- this.db = db;
- this.z = z;
- this.r = r;
- this.u.i = i;
- this.n = n;
- this.flags = flags;
+ ) {
+ this.db = db;
+ this.z = z;
+ this.r = r;
+ this.u.i = i;
+ this.n = n;
+ this.flags = flags;
#if SQLITE_DEBUG
- this.pScopyFrom = pScopyFrom;
- this.pFiller = pFiller;
+ this.pScopyFrom = pScopyFrom;
+ this.pFiller = pFiller;
#endif
- this.type = type;
- this.enc = enc;
- }
-
- public void CopyTo( ref Mem ct )
- {
- if ( ct == null )
- ct = new Mem();
- ct.u = u;
- ct.r = r;
- ct.db = db;
- ct.z = z;
- if ( zBLOB == null )
- ct.zBLOB = null;
- else
- {
- ct.zBLOB = sqlite3Malloc( zBLOB.Length );
- Buffer.BlockCopy( zBLOB, 0, ct.zBLOB, 0, zBLOB.Length );
- }
- ct.n = n;
- ct.flags = flags;
- ct.type = type;
- ct.enc = enc;
- ct.xDel = xDel;
- }
-
- };
-
- /* One or more of the following flags are set to indicate the validOK
- ** representations of the value stored in the Mem struct.
- **
- ** If the MEM_Null flag is set, then the value is an SQL NULL value.
- ** No other flags may be set in this case.
- **
- ** If the MEM_Str flag is set then Mem.z points at a string representation.
- ** Usually this is encoded in the same unicode encoding as the main
- ** database (see below for exceptions). If the MEM_Term flag is also
- ** set, then the string is nul terminated. The MEM_Int and MEM_Real
- ** flags may coexist with the MEM_Str flag.
- */
- //#define MEM_Null 0x0001 /* Value is NULL */
- //#define MEM_Str 0x0002 /* Value is a string */
- //#define MEM_Int 0x0004 /* Value is an integer */
- //#define MEM_Real 0x0008 /* Value is a real number */
- //#define MEM_Blob 0x0010 /* Value is a BLOB */
- //#define MEM_RowSet 0x0020 /* Value is a RowSet object */
- //#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
- //#define MEM_Invalid 0x0080 /* Value is undefined */
- //#define MEM_TypeMask 0x00ff /* Mask of type bits */
- const int MEM_Null = 0x0001;
- const int MEM_Str = 0x0002;
- const int MEM_Int = 0x0004;
- const int MEM_Real = 0x0008;
- const int MEM_Blob = 0x0010;
- const int MEM_RowSet = 0x0020;
- const int MEM_Frame = 0x0040;
- const int MEM_Invalid = 0x0080;
- const int MEM_TypeMask = 0x00ff;
-
- /* Whenever Mem contains a valid string or blob representation, one of
- ** the following flags must be set to determine the memory management
- ** policy for Mem.z. The MEM_Term flag tells us whether or not the
- ** string is \000 or \u0000 terminated
- // */
- //#define MEM_Term 0x0200 /* String rep is nul terminated */
- //#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
- //#define MEM_Static 0x0800 /* Mem.z points to a static string */
- //#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
- //#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
- //#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
- //#if SQLITE_OMIT_INCRBLOB
- // #undef MEM_Zero
- // #define MEM_Zero 0x0000
- //#endif
- const int MEM_Term = 0x0200;
- const int MEM_Dyn = 0x0400;
- const int MEM_Static = 0x0800;
- const int MEM_Ephem = 0x1000;
- const int MEM_Agg = 0x2000;
+ this.type = type;
+ this.enc = enc;
+ }
+
+ public void CopyTo(ref Mem ct) {
+ if (ct == null)
+ ct = new Mem();
+ ct.u = u;
+ ct.r = r;
+ ct.db = db;
+ ct.z = z;
+ if (zBLOB == null)
+ ct.zBLOB = null;
+ else {
+ ct.zBLOB = sqlite3Malloc(zBLOB.Length);
+ Buffer.BlockCopy(zBLOB, 0, ct.zBLOB, 0, zBLOB.Length);
+ }
+ ct.n = n;
+ ct.flags = flags;
+ ct.type = type;
+ ct.enc = enc;
+ ct.xDel = xDel;
+ }
+
+ };
+
+ /* One or more of the following flags are set to indicate the validOK
+ ** representations of the value stored in the Mem struct.
+ **
+ ** If the MEM_Null flag is set, then the value is an SQL NULL value.
+ ** No other flags may be set in this case.
+ **
+ ** If the MEM_Str flag is set then Mem.z points at a string representation.
+ ** Usually this is encoded in the same unicode encoding as the main
+ ** database (see below for exceptions). If the MEM_Term flag is also
+ ** set, then the string is nul terminated. The MEM_Int and MEM_Real
+ ** flags may coexist with the MEM_Str flag.
+ */
+ //#define MEM_Null 0x0001 /* Value is NULL */
+ //#define MEM_Str 0x0002 /* Value is a string */
+ //#define MEM_Int 0x0004 /* Value is an integer */
+ //#define MEM_Real 0x0008 /* Value is a real number */
+ //#define MEM_Blob 0x0010 /* Value is a BLOB */
+ //#define MEM_RowSet 0x0020 /* Value is a RowSet object */
+ //#define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
+ //#define MEM_Invalid 0x0080 /* Value is undefined */
+ //#define MEM_TypeMask 0x00ff /* Mask of type bits */
+ const int MEM_Null = 0x0001;
+ const int MEM_Str = 0x0002;
+ const int MEM_Int = 0x0004;
+ const int MEM_Real = 0x0008;
+ const int MEM_Blob = 0x0010;
+ const int MEM_RowSet = 0x0020;
+ const int MEM_Frame = 0x0040;
+ const int MEM_Invalid = 0x0080;
+ const int MEM_TypeMask = 0x00ff;
+
+ /* Whenever Mem contains a valid string or blob representation, one of
+ ** the following flags must be set to determine the memory management
+ ** policy for Mem.z. The MEM_Term flag tells us whether or not the
+ ** string is \000 or \u0000 terminated
+ // */
+ //#define MEM_Term 0x0200 /* String rep is nul terminated */
+ //#define MEM_Dyn 0x0400 /* Need to call sqliteFree() on Mem.z */
+ //#define MEM_Static 0x0800 /* Mem.z points to a static string */
+ //#define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
+ //#define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
+ //#define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
+ //#if SQLITE_OMIT_INCRBLOB
+ // #undef MEM_Zero
+ // #define MEM_Zero 0x0000
+ //#endif
+ const int MEM_Term = 0x0200;
+ const int MEM_Dyn = 0x0400;
+ const int MEM_Static = 0x0800;
+ const int MEM_Ephem = 0x1000;
+ const int MEM_Agg = 0x2000;
#if !SQLITE_OMIT_INCRBLOB
const int MEM_Zero = 0x4000;
#else
- const int MEM_Zero = 0x0000;
+ const int MEM_Zero = 0x0000;
#endif
- /*
-** Clear any existing type flags from a Mem and replace them with f
-*/
- //#define MemSetTypeFlag(p, f) \
- // ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
- static void MemSetTypeFlag( Mem p, int f )
- {
- p.flags = (u16)( p.flags & ~( MEM_TypeMask | MEM_Zero ) | f );
- }// TODO -- Convert back to inline for speed
-
- /*
- ** Return true if a memory cell is not marked as invalid. This macro
- ** is for use inside Debug.Assert() statements only.
+ /*
+ ** Clear any existing type flags from a Mem and replace them with f
*/
+ //#define MemSetTypeFlag(p, f) \
+ // ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
+ static void MemSetTypeFlag(Mem p, int f) {
+ p.flags = (u16)(p.flags & ~(MEM_TypeMask | MEM_Zero) | f);
+ }// TODO -- Convert back to inline for speed
+
+ /*
+ ** Return true if a memory cell is not marked as invalid. This macro
+ ** is for use inside Debug.Assert() statements only.
+ */
#if SQLITE_DEBUG
- //#define memIsValid(M) ((M)->flags & MEM_Invalid)==0
- static bool memIsValid( Mem M )
- {
- return ( ( M ).flags & MEM_Invalid ) == 0;
- }
+ //#define memIsValid(M) ((M)->flags & MEM_Invalid)==0
+ static bool memIsValid(Mem M) {
+ return ((M).flags & MEM_Invalid) == 0;
+ }
#else
static bool memIsValid( Mem M ) { return true; }
#endif
- /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
-** additional information about auxiliary information bound to arguments
-** of the function. This is used to implement the sqlite3_get_auxdata()
-** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
-** that can be associated with a constant argument to a function. This
-** allows functions such as "regexp" to compile their constant regular
-** expression argument once and reused the compiled code for multiple
-** invocations.
-*/
- public class AuxData
- {
- public object pAux; /* Aux data for the i-th argument */
- //(void ); /* Destructor for the aux data */
- };
-
- public class VdbeFunc : FuncDef
- {
- public FuncDef pFunc; /* The definition of the function */
- public int nAux; /* Number of entries allocated for apAux[] */
- public AuxData[] apAux = new AuxData[2]; /* One slot for each function argument */
- };
-
- /*
- ** The "context" argument for a installable function. A pointer to an
- ** instance of this structure is the first argument to the routines used
- ** implement the SQL functions.
- **
- ** There is a typedef for this structure in sqlite.h. So all routines,
- ** even the public interface to SQLite, can use a pointer to this structure.
- ** But this file is the only place where the internal details of this
- ** structure are known.
- **
- ** This structure is defined inside of vdbeInt.h because it uses substructures
- ** (Mem) which are only defined there.
- */
- public class sqlite3_context
- {
- public FuncDef pFunc; /* Pointer to function information. MUST BE FIRST */
- public VdbeFunc pVdbeFunc; /* Auxilary data, if created. */
- public Mem s = new Mem(); /* The return value is stored here */
- public Mem pMem; /* Memory cell used to store aggregate context */
- public int isError; /* Error code returned by the function. */
- public CollSeq pColl; /* Collating sequence */
-
- };
-
- /*
- ** An instance of the virtual machine. This structure contains the complete
- ** state of the virtual machine.
- **
- ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
- ** is really a pointer to an instance of this structure.
- **
- ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
- ** any virtual table method invocations made by the vdbe program. It is
- ** set to 2 for xDestroy method calls and 1 for all other methods. This
- ** variable is used for two purposes: to allow xDestroy methods to execute
- ** "DROP TABLE" statements and to prevent some nasty side effects of
- ** malloc failure when SQLite is invoked recursively by a virtual table
- ** method function.
+ /* A VdbeFunc is just a FuncDef (defined in sqliteInt.h) that contains
+ ** additional information about auxiliary information bound to arguments
+ ** of the function. This is used to implement the sqlite3_get_auxdata()
+ ** and sqlite3_set_auxdata() APIs. The "auxdata" is some auxiliary data
+ ** that can be associated with a constant argument to a function. This
+ ** allows functions such as "regexp" to compile their constant regular
+ ** expression argument once and reused the compiled code for multiple
+ ** invocations.
*/
- public class Vdbe
- {
- public sqlite3 db; /* The database connection that owns this statement */
- public Op[] aOp; /* Space to hold the virtual machine's program */
- public Mem[] aMem; /* The memory locations */
- public Mem[] apArg; /* Arguments to currently executing user function */
- public Mem[] aColName; /* Column names to return */
- public Mem[] pResultSet; /* Pointer to an array of results */
- public int nMem; /* Number of memory locations currently allocated */
- public int nOp; /* Number of instructions in the program */
- public int nOpAlloc; /* Number of slots allocated for aOp[] */
- public int nLabel; /* Number of labels used */
- public int nLabelAlloc; /* Number of slots allocated in aLabel[] */
- public int[] aLabel; /* Space to hold the labels */
- public u16 nResColumn; /* Number of columns in one row of the result set */
- public u16 nCursor; /* Number of slots in apCsr[] */
- public u32 magic; /* Magic number for sanity checking */
- public string zErrMsg; /* Error message written here */
- public Vdbe pPrev; /* Linked list of VDBEs with the same Vdbe.db */
- public Vdbe pNext; /* Linked list of VDBEs with the same Vdbe.db */
- public VdbeCursor[] apCsr; /* One element of this array for each open cursor */
- public Mem[] aVar; /* Values for the OP_Variable opcode. */
- public string[] azVar; /* Name of variables */
- public ynVar nVar; /* Number of entries in aVar[] */
- public ynVar nzVar; /* Number of entries in azVar[] */
- public u32 cacheCtr; /* VdbeCursor row cache generation counter */
- public int pc; /* The program counter */
- public int rc; /* Value to return */
- public u8 errorAction; /* Recovery action to do in case of an error */
- public int explain; /* True if EXPLAIN present on SQL command */
- public bool changeCntOn; /* True to update the change-counter */
- public bool expired; /* True if the VM needs to be recompiled */
- public u8 runOnlyOnce; /* Automatically expire on reset */
- public int minWriteFileFormat; /* Minimum file format for writable database files */
- public int inVtabMethod; /* See comments above */
- public bool usesStmtJournal; /* True if uses a statement journal */
- public bool readOnly; /* True for read-only statements */
- public int nChange; /* Number of db changes made since last reset */
- public bool isPrepareV2; /* True if prepared with prepare_v2() */
- public yDbMask btreeMask; /* Bitmask of db.aDb[] entries referenced */
- public yDbMask lockMask; /* Subset of btreeMask that requires a lock */
-
- public int iStatement; /* Statement number (or 0 if has not opened stmt) */
- public int[] aCounter = new int[3]; /* Counters used by sqlite3_stmt_status() */
+ public class AuxData {
+ public object pAux; /* Aux data for the i-th argument */
+ //(void ); /* Destructor for the aux data */
+ };
+
+ public class VdbeFunc : FuncDef {
+ public FuncDef pFunc; /* The definition of the function */
+ public int nAux; /* Number of entries allocated for apAux[] */
+ public AuxData[] apAux = new AuxData[2]; /* One slot for each function argument */
+ };
+
+ /*
+ ** The "context" argument for a installable function. A pointer to an
+ ** instance of this structure is the first argument to the routines used
+ ** implement the SQL functions.
+ **
+ ** There is a typedef for this structure in sqlite.h. So all routines,
+ ** even the public interface to SQLite, can use a pointer to this structure.
+ ** But this file is the only place where the internal details of this
+ ** structure are known.
+ **
+ ** This structure is defined inside of vdbeInt.h because it uses substructures
+ ** (Mem) which are only defined there.
+ */
+ public class sqlite3_context {
+ public FuncDef pFunc; /* Pointer to function information. MUST BE FIRST */
+ public VdbeFunc pVdbeFunc; /* Auxilary data, if created. */
+ public Mem s = new Mem(); /* The return value is stored here */
+ public Mem pMem; /* Memory cell used to store aggregate context */
+ public int isError; /* Error code returned by the function. */
+ public CollSeq pColl; /* Collating sequence */
+
+ };
+
+ /*
+ ** An instance of the virtual machine. This structure contains the complete
+ ** state of the virtual machine.
+ **
+ ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
+ ** is really a pointer to an instance of this structure.
+ **
+ ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
+ ** any virtual table method invocations made by the vdbe program. It is
+ ** set to 2 for xDestroy method calls and 1 for all other methods. This
+ ** variable is used for two purposes: to allow xDestroy methods to execute
+ ** "DROP TABLE" statements and to prevent some nasty side effects of
+ ** malloc failure when SQLite is invoked recursively by a virtual table
+ ** method function.
+ */
+ public class Vdbe {
+ public sqlite3 db; /* The database connection that owns this statement */
+ public Op[] aOp; /* Space to hold the virtual machine's program */
+ public Mem[] aMem; /* The memory locations */
+ public Mem[] apArg; /* Arguments to currently executing user function */
+ public Mem[] aColName; /* Column names to return */
+ public Mem[] pResultSet; /* Pointer to an array of results */
+ public int nMem; /* Number of memory locations currently allocated */
+ public int nOp; /* Number of instructions in the program */
+ public int nOpAlloc; /* Number of slots allocated for aOp[] */
+ public int nLabel; /* Number of labels used */
+ public int nLabelAlloc; /* Number of slots allocated in aLabel[] */
+ public int[] aLabel; /* Space to hold the labels */
+ public u16 nResColumn; /* Number of columns in one row of the result set */
+ public u16 nCursor; /* Number of slots in apCsr[] */
+ public u32 magic; /* Magic number for sanity checking */
+ public string zErrMsg; /* Error message written here */
+ public Vdbe pPrev; /* Linked list of VDBEs with the same Vdbe.db */
+ public Vdbe pNext; /* Linked list of VDBEs with the same Vdbe.db */
+ public VdbeCursor[] apCsr; /* One element of this array for each open cursor */
+ public Mem[] aVar; /* Values for the OP_Variable opcode. */
+ public string[] azVar; /* Name of variables */
+ public ynVar nVar; /* Number of entries in aVar[] */
+ public ynVar nzVar; /* Number of entries in azVar[] */
+ public u32 cacheCtr; /* VdbeCursor row cache generation counter */
+ public int pc; /* The program counter */
+ public int rc; /* Value to return */
+ public u8 errorAction; /* Recovery action to do in case of an error */
+ public int explain; /* True if EXPLAIN present on SQL command */
+ public bool changeCntOn; /* True to update the change-counter */
+ public bool expired; /* True if the VM needs to be recompiled */
+ public u8 runOnlyOnce; /* Automatically expire on reset */
+ public int minWriteFileFormat; /* Minimum file format for writable database files */
+ public int inVtabMethod; /* See comments above */
+ public bool usesStmtJournal; /* True if uses a statement journal */
+ public bool readOnly; /* True for read-only statements */
+ public int nChange; /* Number of db changes made since last reset */
+ public bool isPrepareV2; /* True if prepared with prepare_v2() */
+ public yDbMask btreeMask; /* Bitmask of db.aDb[] entries referenced */
+ public yDbMask lockMask; /* Subset of btreeMask that requires a lock */
+
+ public int iStatement; /* Statement number (or 0 if has not opened stmt) */
+ public int[] aCounter = new int[3]; /* Counters used by sqlite3_stmt_status() */
#if !SQLITE_OMIT_TRACE
- public i64 startTime; /* Time when query started - used for profiling */
+ public i64 startTime; /* Time when query started - used for profiling */
#endif
- public i64 nFkConstraint; /* Number of imm. FK constraints this VM */
- public i64 nStmtDefCons; /* Number of def. constraints when stmt started */
- public string zSql = ""; /* Text of the SQL statement that generated this */
- public object pFree; /* Free this when deleting the vdbe */
+ public i64 nFkConstraint; /* Number of imm. FK constraints this VM */
+ public i64 nStmtDefCons; /* Number of def. constraints when stmt started */
+ public string zSql = ""; /* Text of the SQL statement that generated this */
+ public object pFree; /* Free this when deleting the vdbe */
#if SQLITE_DEBUG
- public FILE trace; /* Write an execution trace here, if not NULL */
+ public FILE trace; /* Write an execution trace here, if not NULL */
#endif
- public VdbeFrame pFrame; /* Parent frame */
- public VdbeFrame pDelFrame; /* List of frame objects to free on VM reset */
- public int nFrame; /* Number of frames in pFrame list */
- public u32 expmask; /* Binding to these vars invalidates VM */
- public SubProgram pProgram; /* Linked list of all sub-programs used by VM */
-
- public Vdbe Copy()
- {
- Vdbe cp = (Vdbe)MemberwiseClone();
- return cp;
- }
- public void CopyTo( Vdbe ct )
- {
- ct.db = db;
- ct.pPrev = pPrev;
- ct.pNext = pNext;
- ct.nOp = nOp;
- ct.nOpAlloc = nOpAlloc;
- ct.aOp = aOp;
- ct.nLabel = nLabel;
- ct.nLabelAlloc = nLabelAlloc;
- ct.aLabel = aLabel;
- ct.apArg = apArg;
- ct.aColName = aColName;
- ct.nCursor = nCursor;
- ct.apCsr = apCsr;
- ct.aVar = aVar;
- ct.azVar = azVar;
- ct.nVar = nVar;
- ct.nzVar = nzVar;
- ct.magic = magic;
- ct.nMem = nMem;
- ct.aMem = aMem;
- ct.cacheCtr = cacheCtr;
- ct.pc = pc;
- ct.rc = rc;
- ct.errorAction = errorAction;
- ct.nResColumn = nResColumn;
- ct.zErrMsg = zErrMsg;
- ct.pResultSet = pResultSet;
- ct.explain = explain;
- ct.changeCntOn = changeCntOn;
- ct.expired = expired;
- ct.minWriteFileFormat = minWriteFileFormat;
- ct.inVtabMethod = inVtabMethod;
- ct.usesStmtJournal = usesStmtJournal;
- ct.readOnly = readOnly;
- ct.nChange = nChange;
- ct.isPrepareV2 = isPrepareV2;
+ public VdbeFrame pFrame; /* Parent frame */
+ public VdbeFrame pDelFrame; /* List of frame objects to free on VM reset */
+ public int nFrame; /* Number of frames in pFrame list */
+ public u32 expmask; /* Binding to these vars invalidates VM */
+ public SubProgram pProgram; /* Linked list of all sub-programs used by VM */
+
+ public Vdbe Copy() {
+ Vdbe cp = (Vdbe)MemberwiseClone();
+ return cp;
+ }
+ public void CopyTo(Vdbe ct) {
+ ct.db = db;
+ ct.pPrev = pPrev;
+ ct.pNext = pNext;
+ ct.nOp = nOp;
+ ct.nOpAlloc = nOpAlloc;
+ ct.aOp = aOp;
+ ct.nLabel = nLabel;
+ ct.nLabelAlloc = nLabelAlloc;
+ ct.aLabel = aLabel;
+ ct.apArg = apArg;
+ ct.aColName = aColName;
+ ct.nCursor = nCursor;
+ ct.apCsr = apCsr;
+ ct.aVar = aVar;
+ ct.azVar = azVar;
+ ct.nVar = nVar;
+ ct.nzVar = nzVar;
+ ct.magic = magic;
+ ct.nMem = nMem;
+ ct.aMem = aMem;
+ ct.cacheCtr = cacheCtr;
+ ct.pc = pc;
+ ct.rc = rc;
+ ct.errorAction = errorAction;
+ ct.nResColumn = nResColumn;
+ ct.zErrMsg = zErrMsg;
+ ct.pResultSet = pResultSet;
+ ct.explain = explain;
+ ct.changeCntOn = changeCntOn;
+ ct.expired = expired;
+ ct.minWriteFileFormat = minWriteFileFormat;
+ ct.inVtabMethod = inVtabMethod;
+ ct.usesStmtJournal = usesStmtJournal;
+ ct.readOnly = readOnly;
+ ct.nChange = nChange;
+ ct.isPrepareV2 = isPrepareV2;
#if !SQLITE_OMIT_TRACE
- ct.startTime = startTime;
+ ct.startTime = startTime;
#endif
- ct.btreeMask = btreeMask;
- ct.lockMask = lockMask;
- aCounter.CopyTo( ct.aCounter, 0 );
- ct.zSql = zSql;
- ct.pFree = pFree;
+ ct.btreeMask = btreeMask;
+ ct.lockMask = lockMask;
+ aCounter.CopyTo(ct.aCounter, 0);
+ ct.zSql = zSql;
+ ct.pFree = pFree;
#if SQLITE_DEBUG
- ct.trace = trace;
+ ct.trace = trace;
#endif
- ct.nFkConstraint = nFkConstraint;
- ct.nStmtDefCons = nStmtDefCons;
- ct.iStatement = iStatement;
- ct.pFrame = pFrame;
- ct.nFrame = nFrame;
- ct.expmask = expmask;
- ct.pProgram = pProgram;
+ ct.nFkConstraint = nFkConstraint;
+ ct.nStmtDefCons = nStmtDefCons;
+ ct.iStatement = iStatement;
+ ct.pFrame = pFrame;
+ ct.nFrame = nFrame;
+ ct.expmask = expmask;
+ ct.pProgram = pProgram;
#if SQLITE_SSE
ct.fetchId=fetchId;
ct.lru=lru;
@@ -562,119 +539,116 @@ public void CopyTo( Vdbe ct )
ct.pLruPrev=pLruPrev;
ct.pLruNext=pLruNext;
#endif
- }
- };
-
- /*
- ** The following are allowed values for Vdbe.magic
- */
- //#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
- //#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
- //#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
- //#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
- const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */
- const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */
- const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */
- const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */
- /*
- ** Function prototypes
- */
- //void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor);
- //void sqliteVdbePopStack(Vdbe*,int);
- //int sqlite3VdbeCursorMoveto(VdbeCursor);
- //#if (SQLITE_DEBUG) || defined(VDBE_PROFILE)
- //void sqlite3VdbePrintOp(FILE*, int, Op);
- //#endif
- //u32 sqlite3VdbeSerialTypeLen(u32);
- //u32 sqlite3VdbeSerialType(Mem*, int);
- //u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
- //u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem);
- //void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
-
- //int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int );
- //int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int);
- //int sqlite3VdbeIdxRowid(sqlite3 *, i64 );
- //int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq);
- //int sqlite3VdbeExec(Vdbe);
- //int sqlite3VdbeList(Vdbe);
- //int sqlite3VdbeHalt(Vdbe);
- //int sqlite3VdbeChangeEncoding(Mem *, int);
- //int sqlite3VdbeMemTooBig(Mem);
- //int sqlite3VdbeMemCopy(Mem*, const Mem);
- //void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
- //void sqlite3VdbeMemMove(Mem*, Mem);
- //int sqlite3VdbeMemNulTerminate(Mem);
- //int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void()(void));
- //void sqlite3VdbeMemSetInt64(Mem*, i64);
+ }
+ };
+
+ /*
+ ** The following are allowed values for Vdbe.magic
+ */
+ //#define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
+ //#define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
+ //#define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
+ //#define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
+ const u32 VDBE_MAGIC_INIT = 0x26bceaa5; /* Building a VDBE program */
+ const u32 VDBE_MAGIC_RUN = 0xbdf20da3; /* VDBE is ready to execute */
+ const u32 VDBE_MAGIC_HALT = 0x519c2973; /* VDBE has completed execution */
+ const u32 VDBE_MAGIC_DEAD = 0xb606c3c8; /* The VDBE has been deallocated */
+ /*
+ ** Function prototypes
+ */
+ //void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor);
+ //void sqliteVdbePopStack(Vdbe*,int);
+ //int sqlite3VdbeCursorMoveto(VdbeCursor);
+ //#if (SQLITE_DEBUG) || defined(VDBE_PROFILE)
+ //void sqlite3VdbePrintOp(FILE*, int, Op);
+ //#endif
+ //u32 sqlite3VdbeSerialTypeLen(u32);
+ //u32 sqlite3VdbeSerialType(Mem*, int);
+ //u32sqlite3VdbeSerialPut(unsigned char*, int, Mem*, int);
+ //u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem);
+ //void sqlite3VdbeDeleteAuxData(VdbeFunc*, int);
+
+ //int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int );
+ //int sqlite3VdbeIdxKeyCompare(VdbeCursor*,UnpackedRecord*,int);
+ //int sqlite3VdbeIdxRowid(sqlite3 *, i64 );
+ //int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq);
+ //int sqlite3VdbeExec(Vdbe);
+ //int sqlite3VdbeList(Vdbe);
+ //int sqlite3VdbeHalt(Vdbe);
+ //int sqlite3VdbeChangeEncoding(Mem *, int);
+ //int sqlite3VdbeMemTooBig(Mem);
+ //int sqlite3VdbeMemCopy(Mem*, const Mem);
+ //void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
+ //void sqlite3VdbeMemMove(Mem*, Mem);
+ //int sqlite3VdbeMemNulTerminate(Mem);
+ //int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void()(void));
+ //void sqlite3VdbeMemSetInt64(Mem*, i64);
#if SQLITE_OMIT_FLOATING_POINT
//# define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
#else
- //void sqlite3VdbeMemSetDouble(Mem*, double);
+ //void sqlite3VdbeMemSetDouble(Mem*, double);
#endif
- //void sqlite3VdbeMemSetNull(Mem);
- //void sqlite3VdbeMemSetZeroBlob(Mem*,int);
- //void sqlite3VdbeMemSetRowSet(Mem);
- //int sqlite3VdbeMemMakeWriteable(Mem);
- //int sqlite3VdbeMemStringify(Mem*, int);
- //i64 sqlite3VdbeIntValue(Mem);
- //int sqlite3VdbeMemIntegerify(Mem);
- //double sqlite3VdbeRealValue(Mem);
- //void sqlite3VdbeIntegerAffinity(Mem);
- //int sqlite3VdbeMemRealify(Mem);
- //int sqlite3VdbeMemNumerify(Mem);
- //int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem);
- //void sqlite3VdbeMemRelease(Mem p);
- //void sqlite3VdbeMemReleaseExternal(Mem p);
- //int sqlite3VdbeMemFinalize(Mem*, FuncDef);
- //string sqlite3OpcodeName(int);
- //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve);
- //int sqlite3VdbeCloseStatement(Vdbe *, int);
- //void sqlite3VdbeFrameDelete(VdbeFrame);
- //int sqlite3VdbeFrameRestore(VdbeFrame );
- //void sqlite3VdbeMemStoreType(Mem *pMem);
+ //void sqlite3VdbeMemSetNull(Mem);
+ //void sqlite3VdbeMemSetZeroBlob(Mem*,int);
+ //void sqlite3VdbeMemSetRowSet(Mem);
+ //int sqlite3VdbeMemMakeWriteable(Mem);
+ //int sqlite3VdbeMemStringify(Mem*, int);
+ //i64 sqlite3VdbeIntValue(Mem);
+ //int sqlite3VdbeMemIntegerify(Mem);
+ //double sqlite3VdbeRealValue(Mem);
+ //void sqlite3VdbeIntegerAffinity(Mem);
+ //int sqlite3VdbeMemRealify(Mem);
+ //int sqlite3VdbeMemNumerify(Mem);
+ //int sqlite3VdbeMemFromBtree(BtCursor*,int,int,int,Mem);
+ //void sqlite3VdbeMemRelease(Mem p);
+ //void sqlite3VdbeMemReleaseExternal(Mem p);
+ //int sqlite3VdbeMemFinalize(Mem*, FuncDef);
+ //string sqlite3OpcodeName(int);
+ //int sqlite3VdbeMemGrow(Mem pMem, int n, int preserve);
+ //int sqlite3VdbeCloseStatement(Vdbe *, int);
+ //void sqlite3VdbeFrameDelete(VdbeFrame);
+ //int sqlite3VdbeFrameRestore(VdbeFrame );
+ //void sqlite3VdbeMemStoreType(Mem *pMem);
#if !(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE//>0
//void sqlite3VdbeEnter(Vdbe);
//void sqlite3VdbeLeave(Vdbe);
#else
-//# define sqlite3VdbeEnter(X)
- static void sqlite3VdbeEnter( Vdbe p )
- {
- }
-//# define sqlite3VdbeLeave(X)
- static void sqlite3VdbeLeave( Vdbe p )
- {
- }
+ //# define sqlite3VdbeEnter(X)
+ static void sqlite3VdbeEnter(Vdbe p) {
+ }
+ //# define sqlite3VdbeLeave(X)
+ static void sqlite3VdbeLeave(Vdbe p) {
+ }
#endif
#if SQLITE_DEBUG
- //void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem);
+ //void sqlite3VdbeMemPrepareToChange(Vdbe*,Mem);
#endif
#if !SQLITE_OMIT_FOREIGN_KEY
- //int sqlite3VdbeCheckFk(Vdbe *, int);
+ //int sqlite3VdbeCheckFk(Vdbe *, int);
#else
//# define sqlite3VdbeCheckFk(p,i) 0
static int sqlite3VdbeCheckFk( Vdbe p, int i ) { return 0; }
#endif
- //int sqlite3VdbeMemTranslate(Mem*, u8);
- //#if SQLITE_DEBUG
- // void sqlite3VdbePrintSql(Vdbe);
- // void sqlite3VdbeMemPrettyPrint(Mem pMem, string zBuf);
- //#endif
- //int sqlite3VdbeMemHandleBom(Mem pMem);
+ //int sqlite3VdbeMemTranslate(Mem*, u8);
+ //#if SQLITE_DEBUG
+ // void sqlite3VdbePrintSql(Vdbe);
+ // void sqlite3VdbeMemPrettyPrint(Mem pMem, string zBuf);
+ //#endif
+ //int sqlite3VdbeMemHandleBom(Mem pMem);
#if !SQLITE_OMIT_INCRBLOB
// int sqlite3VdbeMemExpandBlob(Mem );
#else
- // #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
- static int sqlite3VdbeMemExpandBlob( Mem x )
- {
- return SQLITE_OK;
- }
+ // #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
+ static int sqlite3VdbeMemExpandBlob(Mem x) {
+ return SQLITE_OK;
+ }
#endif
- //#endif //* !_VDBEINT_H_) */
- }
+ //#endif //* !_VDBEINT_H_) */
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/Vdbe_h.cs b/Src/IronPython.SQLite/c#sqlite/Vdbe_h.cs
index 28d39cb07..250ba71cc 100644
--- a/Src/IronPython.SQLite/c#sqlite/Vdbe_h.cs
+++ b/Src/IronPython.SQLite/c#sqlite/Vdbe_h.cs
@@ -1,83 +1,78 @@
using i64 = System.Int64;
using u8 = System.Byte;
-using u64 = System.UInt64;
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** Header file for the Virtual DataBase Engine (VDBE)
- **
- ** This header defines the interface to the virtual database engine
- ** or VDBE. The VDBE implements an abstract machine that runs a
- ** simple program to access and modify the underlying database.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#if !_SQLITE_VDBE_H_
- //#define _SQLITE_VDBE_H_
- //#include
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** Header file for the Virtual DataBase Engine (VDBE)
+ **
+ ** This header defines the interface to the virtual database engine
+ ** or VDBE. The VDBE implements an abstract machine that runs a
+ ** simple program to access and modify the underlying database.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#if !_SQLITE_VDBE_H_
+ //#define _SQLITE_VDBE_H_
+ //#include
- /*
- ** A single VDBE is an opaque structure named "Vdbe". Only routines
- ** in the source file sqliteVdbe.c are allowed to see the insides
- ** of this structure.
- */
- //typedef struct Vdbe Vdbe;
+ /*
+ ** A single VDBE is an opaque structure named "Vdbe". Only routines
+ ** in the source file sqliteVdbe.c are allowed to see the insides
+ ** of this structure.
+ */
+ //typedef struct Vdbe Vdbe;
- /*
- ** The names of the following types declared in vdbeInt.h are required
- ** for the VdbeOp definition.
- */
- //typedef struct VdbeFunc VdbeFunc;
- //typedef struct Mem Mem;
- //typedef struct SubProgram SubProgram;
+ /*
+ ** The names of the following types declared in vdbeInt.h are required
+ ** for the VdbeOp definition.
+ */
+ //typedef struct VdbeFunc VdbeFunc;
+ //typedef struct Mem Mem;
+ //typedef struct SubProgram SubProgram;
- /*
- ** A single instruction of the virtual machine has an opcode
- ** and as many as three operands. The instruction is recorded
- ** as an instance of the following structure:
- */
- public class union_p4
- { /* fourth parameter */
- public int i; /* Integer value if p4type==P4_INT32 */
- public object p; /* Generic pointer */
- //public string z; /* Pointer to data for string (char array) types */
- public string z; // In C# string is unicode, so use byte[] instead
- public i64 pI64; /* Used when p4type is P4_INT64 */
- public double pReal; /* Used when p4type is P4_REAL */
- public FuncDef pFunc; /* Used when p4type is P4_FUNCDEF */
- public VdbeFunc pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
- public CollSeq pColl; /* Used when p4type is P4_COLLSEQ */
- public Mem pMem; /* Used when p4type is P4_MEM */
- public VTable pVtab; /* Used when p4type is P4_VTAB */
- public KeyInfo pKeyInfo; /* Used when p4type is P4_KEYINFO */
- public int[] ai; /* Used when p4type is P4_INTARRAY */
- public SubProgram pProgram; /* Used when p4type is P4_SUBPROGRAM */
- public dxDel pFuncDel; /* Used when p4type is P4_FUNCDEL */
- } ;
- public class VdbeOp
- {
- public u8 opcode; /* What operation to perform */
- public int p4type; /* One of the P4_xxx constants for p4 */
- public u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
- public u8 p5; /* Fifth parameter is an unsigned character */
+ /*
+ ** A single instruction of the virtual machine has an opcode
+ ** and as many as three operands. The instruction is recorded
+ ** as an instance of the following structure:
+ */
+ public class union_p4 { /* fourth parameter */
+ public int i; /* Integer value if p4type==P4_INT32 */
+ public object p; /* Generic pointer */
+ //public string z; /* Pointer to data for string (char array) types */
+ public string z; // In C# string is unicode, so use byte[] instead
+ public i64 pI64; /* Used when p4type is P4_INT64 */
+ public double pReal; /* Used when p4type is P4_REAL */
+ public FuncDef pFunc; /* Used when p4type is P4_FUNCDEF */
+ public VdbeFunc pVdbeFunc; /* Used when p4type is P4_VDBEFUNC */
+ public CollSeq pColl; /* Used when p4type is P4_COLLSEQ */
+ public Mem pMem; /* Used when p4type is P4_MEM */
+ public VTable pVtab; /* Used when p4type is P4_VTAB */
+ public KeyInfo pKeyInfo; /* Used when p4type is P4_KEYINFO */
+ public int[] ai; /* Used when p4type is P4_INTARRAY */
+ public SubProgram pProgram; /* Used when p4type is P4_SUBPROGRAM */
+ public dxDel pFuncDel; /* Used when p4type is P4_FUNCDEL */
+ };
+ public class VdbeOp {
+ public u8 opcode; /* What operation to perform */
+ public int p4type; /* One of the P4_xxx constants for p4 */
+ public u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
+ public u8 p5; /* Fifth parameter is an unsigned character */
#if DEBUG_CLASS_VDBEOP || DEBUG_CLASS_ALL
public int _p1; /* First operand */
public int p1
@@ -100,212 +95,206 @@ public int p3
set { _p3 = value; }
}
#else
- public int p1; /* First operand */
- public int p2; /* Second parameter (often the jump destination) */
- public int p3; /* The third parameter */
+ public int p1; /* First operand */
+ public int p2; /* Second parameter (often the jump destination) */
+ public int p3; /* The third parameter */
#endif
- public union_p4 p4 = new union_p4();
+ public union_p4 p4 = new union_p4();
#if SQLITE_DEBUG || DEBUG
- public string zComment; /* Comment to improve readability */
+ public string zComment; /* Comment to improve readability */
#endif
#if VDBE_PROFILE
public int cnt; /* Number of times this instruction was executed */
public u64 cycles; /* Total time spend executing this instruction */
#endif
- };
- //typedef struct VdbeOp VdbeOp;
+ };
+ //typedef struct VdbeOp VdbeOp;
- /*
- ** A sub-routine used to implement a trigger program.
- */
- public class SubProgram
- {
- public VdbeOp[] aOp; /* Array of opcodes for sub-program */
- public int nOp; /* Elements in aOp[] */
- public int nMem; /* Number of memory cells required */
- public int nCsr; /* Number of cursors required */
- public int token; /* id that may be used to recursive triggers */
- public SubProgram pNext; /* Next sub-program already visited */
- };
+ /*
+ ** A sub-routine used to implement a trigger program.
+ */
+ public class SubProgram {
+ public VdbeOp[] aOp; /* Array of opcodes for sub-program */
+ public int nOp; /* Elements in aOp[] */
+ public int nMem; /* Number of memory cells required */
+ public int nCsr; /* Number of cursors required */
+ public int token; /* id that may be used to recursive triggers */
+ public SubProgram pNext; /* Next sub-program already visited */
+ };
- /*
- ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
- ** it takes up less space.
- */
- public struct VdbeOpList
- {
- public u8 opcode; /* What operation to perform */
- public int p1; /* First operand */
- public int p2; /* Second parameter (often the jump destination) */
- public int p3; /* Third parameter */
- public VdbeOpList( u8 opcode, int p1, int p2, int p3 )
- {
- this.opcode = opcode;
- this.p1 = p1;
- this.p2 = p2;
- this.p3 = p3;
- }
+ /*
+ ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
+ ** it takes up less space.
+ */
+ public struct VdbeOpList {
+ public u8 opcode; /* What operation to perform */
+ public int p1; /* First operand */
+ public int p2; /* Second parameter (often the jump destination) */
+ public int p3; /* Third parameter */
+ public VdbeOpList(u8 opcode, int p1, int p2, int p3) {
+ this.opcode = opcode;
+ this.p1 = p1;
+ this.p2 = p2;
+ this.p3 = p3;
+ }
- };
- //typedef struct VdbeOpList VdbeOpList;
+ };
+ //typedef struct VdbeOpList VdbeOpList;
- /*
- ** Allowed values of VdbeOp.p4type
- */
- const int P4_NOTUSED = 0; /* The P4 parameter is not used */
- const int P4_DYNAMIC = ( -1 ); /* Pointer to a string obtained from sqliteMalloc=(); */
- const int P4_STATIC = ( -2 ); /* Pointer to a static string */
- const int P4_COLLSEQ = ( -4 ); /* P4 is a pointer to a CollSeq structure */
- const int P4_FUNCDEF = ( -5 ); /* P4 is a pointer to a FuncDef structure */
- const int P4_KEYINFO = ( -6 ); /* P4 is a pointer to a KeyInfo structure */
- const int P4_VDBEFUNC = ( -7 ); /* P4 is a pointer to a VdbeFunc structure */
- const int P4_MEM = ( -8 ); /* P4 is a pointer to a Mem* structure */
- const int P4_TRANSIENT = 0; /* P4 is a pointer to a transient string */
- const int P4_VTAB = ( -10 ); /* P4 is a pointer to an sqlite3_vtab structure */
- const int P4_MPRINTF = ( -11 ); /* P4 is a string obtained from sqlite3_mprintf=(); */
- const int P4_REAL = ( -12 ); /* P4 is a 64-bit floating point value */
- const int P4_INT64 = ( -13 ); /* P4 is a 64-bit signed integer */
- const int P4_INT32 = ( -14 ); /* P4 is a 32-bit signed integer */
- const int P4_INTARRAY = ( -15 ); /* #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
- const int P4_SUBPROGRAM = ( -18 );/* #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
+ /*
+ ** Allowed values of VdbeOp.p4type
+ */
+ const int P4_NOTUSED = 0; /* The P4 parameter is not used */
+ const int P4_DYNAMIC = (-1); /* Pointer to a string obtained from sqliteMalloc=(); */
+ const int P4_STATIC = (-2); /* Pointer to a static string */
+ const int P4_COLLSEQ = (-4); /* P4 is a pointer to a CollSeq structure */
+ const int P4_FUNCDEF = (-5); /* P4 is a pointer to a FuncDef structure */
+ const int P4_KEYINFO = (-6); /* P4 is a pointer to a KeyInfo structure */
+ const int P4_VDBEFUNC = (-7); /* P4 is a pointer to a VdbeFunc structure */
+ const int P4_MEM = (-8); /* P4 is a pointer to a Mem* structure */
+ const int P4_TRANSIENT = 0; /* P4 is a pointer to a transient string */
+ const int P4_VTAB = (-10); /* P4 is a pointer to an sqlite3_vtab structure */
+ const int P4_MPRINTF = (-11); /* P4 is a string obtained from sqlite3_mprintf=(); */
+ const int P4_REAL = (-12); /* P4 is a 64-bit floating point value */
+ const int P4_INT64 = (-13); /* P4 is a 64-bit signed integer */
+ const int P4_INT32 = (-14); /* P4 is a 32-bit signed integer */
+ const int P4_INTARRAY = (-15); /* #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
+ const int P4_SUBPROGRAM = (-18);/* #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
- /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
- ** is made. That copy is freed when the Vdbe is finalized. But if the
- ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
- ** gets freed when the Vdbe is finalized so it still should be obtained
- ** from a single sqliteMalloc(). But no copy is made and the calling
- ** function should *not* try to free the KeyInfo.
- */
- const int P4_KEYINFO_HANDOFF = ( -16 ); // #define P4_KEYINFO_HANDOFF (-16)
- const int P4_KEYINFO_STATIC = ( -17 ); // #define P4_KEYINFO_STATIC (-17)
+ /* When adding a P4 argument using P4_KEYINFO, a copy of the KeyInfo structure
+ ** is made. That copy is freed when the Vdbe is finalized. But if the
+ ** argument is P4_KEYINFO_HANDOFF, the passed in pointer is used. It still
+ ** gets freed when the Vdbe is finalized so it still should be obtained
+ ** from a single sqliteMalloc(). But no copy is made and the calling
+ ** function should *not* try to free the KeyInfo.
+ */
+ const int P4_KEYINFO_HANDOFF = (-16); // #define P4_KEYINFO_HANDOFF (-16)
+ const int P4_KEYINFO_STATIC = (-17); // #define P4_KEYINFO_STATIC (-17)
- /*
- ** The Vdbe.aColName array contains 5n Mem structures, where n is the
- ** number of columns of data returned by the statement.
- */
- //#define COLNAME_NAME 0
- //#define COLNAME_DECLTYPE 1
- //#define COLNAME_DATABASE 2
- //#define COLNAME_TABLE 3
- //#define COLNAME_COLUMN 4
- //#if SQLITE_ENABLE_COLUMN_METADATA
- //# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
- //#else
- //# ifdef SQLITE_OMIT_DECLTYPE
- //# define COLNAME_N 1 /* Store only the name */
- //# else
- //# define COLNAME_N 2 /* Store the name and decltype */
- //# endif
- //#endif
- const int COLNAME_NAME = 0;
- const int COLNAME_DECLTYPE = 1;
- const int COLNAME_DATABASE = 2;
- const int COLNAME_TABLE = 3;
- const int COLNAME_COLUMN = 4;
+ /*
+ ** The Vdbe.aColName array contains 5n Mem structures, where n is the
+ ** number of columns of data returned by the statement.
+ */
+ //#define COLNAME_NAME 0
+ //#define COLNAME_DECLTYPE 1
+ //#define COLNAME_DATABASE 2
+ //#define COLNAME_TABLE 3
+ //#define COLNAME_COLUMN 4
+ //#if SQLITE_ENABLE_COLUMN_METADATA
+ //# define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
+ //#else
+ //# ifdef SQLITE_OMIT_DECLTYPE
+ //# define COLNAME_N 1 /* Store only the name */
+ //# else
+ //# define COLNAME_N 2 /* Store the name and decltype */
+ //# endif
+ //#endif
+ const int COLNAME_NAME = 0;
+ const int COLNAME_DECLTYPE = 1;
+ const int COLNAME_DATABASE = 2;
+ const int COLNAME_TABLE = 3;
+ const int COLNAME_COLUMN = 4;
#if SQLITE_ENABLE_COLUMN_METADATA
-const int COLNAME_N = 5; /* Number of COLNAME_xxx symbols */
+ const int COLNAME_N = 5; /* Number of COLNAME_xxx symbols */
#else
-# if SQLITE_OMIT_DECLTYPE
+#if SQLITE_OMIT_DECLTYPE
const int COLNAME_N = 1; /* Number of COLNAME_xxx symbols */
-# else
+#else
const int COLNAME_N = 2;
-# endif
+#endif
#endif
- /*
-** The following macro converts a relative address in the p2 field
-** of a VdbeOp structure into a negative number so that
-** sqlite3VdbeAddOpList() knows that the address is relative. Calling
-** the macro again restores the address.
-*/
- //#define ADDR(X) (-1-(X))
- static int ADDR( int x )
- {
- return -1 - x;
- }
- /*
- ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
- ** header file that defines a number for each opcode used by the VDBE.
+ /*
+ ** The following macro converts a relative address in the p2 field
+ ** of a VdbeOp structure into a negative number so that
+ ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
+ ** the macro again restores the address.
*/
- //#include "opcodes.h"
+ //#define ADDR(X) (-1-(X))
+ static int ADDR(int x) {
+ return -1 - x;
+ }
+ /*
+ ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
+ ** header file that defines a number for each opcode used by the VDBE.
+ */
+ //#include "opcodes.h"
- /*
- ** Prototypes for the VDBE interface. See comments on the implementation
- ** for a description of what each of these routines does.
- */
- /*
- ** Prototypes for the VDBE interface. See comments on the implementation
- ** for a description of what each of these routines does.
- */
- //Vdbe *sqlite3VdbeCreate(sqlite3);
- //int sqlite3VdbeAddOp0(Vdbe*,int);
- //int sqlite3VdbeAddOp1(Vdbe*,int,int);
- //int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
- //int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
- //int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,string zP4,int);
- //int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
- //int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
- //void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char);
- //void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
- //void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
- //void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
- //void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
- //void sqlite3VdbeJumpHere(Vdbe*, int addr);
- //void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
- //void sqlite3VdbeChangeP4(Vdbe*, int addr, string zP4, int N);
- //void sqlite3VdbeUsesBtree(Vdbe*, int);
- //VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
- //int sqlite3VdbeMakeLabel(Vdbe);
- //void sqlite3VdbeRunOnlyOnce(Vdbe);
- //void sqlite3VdbeDelete(Vdbe);
- //void sqlite3VdbeDeleteObject(sqlite3*,Vdbe);
- //void sqlite3VdbeMakeReady(Vdbe*,Parse);
- //int sqlite3VdbeFinalize(Vdbe);
- //void sqlite3VdbeResolveLabel(Vdbe*, int);
- //int sqlite3VdbeCurrentAddr(Vdbe);
- //#if SQLITE_DEBUG
- // int sqlite3VdbeAssertMayAbort(Vdbe *, int);
- // void sqlite3VdbeTrace(Vdbe*,FILE);
- //#endif
- //void sqlite3VdbeResetStepResult(Vdbe);
- //void sqlite3VdbeRewind(Vdbe);
- //int sqlite3VdbeReset(Vdbe);
- //void sqlite3VdbeSetNumCols(Vdbe*,int);
- //int sqlite3VdbeSetColName(Vdbe*, int, int, string , void()(void));
- //void sqlite3VdbeCountChanges(Vdbe);
- //sqlite3 *sqlite3VdbeDb(Vdbe);
- //void sqlite3VdbeSetSql(Vdbe*, string z, int n, int);
- //void sqlite3VdbeSwap(Vdbe*,Vdbe);
- //VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int);
- //sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
- //void sqlite3VdbeSetVarmask(Vdbe*, int);
- //#if !SQLITE_OMIT_TRACE
- // char *sqlite3VdbeExpandSql(Vdbe*, const char);
- //#endif
+ /*
+ ** Prototypes for the VDBE interface. See comments on the implementation
+ ** for a description of what each of these routines does.
+ */
+ /*
+ ** Prototypes for the VDBE interface. See comments on the implementation
+ ** for a description of what each of these routines does.
+ */
+ //Vdbe *sqlite3VdbeCreate(sqlite3);
+ //int sqlite3VdbeAddOp0(Vdbe*,int);
+ //int sqlite3VdbeAddOp1(Vdbe*,int,int);
+ //int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
+ //int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
+ //int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,string zP4,int);
+ //int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
+ //int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp);
+ //void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char);
+ //void sqlite3VdbeChangeP1(Vdbe*, int addr, int P1);
+ //void sqlite3VdbeChangeP2(Vdbe*, int addr, int P2);
+ //void sqlite3VdbeChangeP3(Vdbe*, int addr, int P3);
+ //void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
+ //void sqlite3VdbeJumpHere(Vdbe*, int addr);
+ //void sqlite3VdbeChangeToNoop(Vdbe*, int addr, int N);
+ //void sqlite3VdbeChangeP4(Vdbe*, int addr, string zP4, int N);
+ //void sqlite3VdbeUsesBtree(Vdbe*, int);
+ //VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
+ //int sqlite3VdbeMakeLabel(Vdbe);
+ //void sqlite3VdbeRunOnlyOnce(Vdbe);
+ //void sqlite3VdbeDelete(Vdbe);
+ //void sqlite3VdbeDeleteObject(sqlite3*,Vdbe);
+ //void sqlite3VdbeMakeReady(Vdbe*,Parse);
+ //int sqlite3VdbeFinalize(Vdbe);
+ //void sqlite3VdbeResolveLabel(Vdbe*, int);
+ //int sqlite3VdbeCurrentAddr(Vdbe);
+ //#if SQLITE_DEBUG
+ // int sqlite3VdbeAssertMayAbort(Vdbe *, int);
+ // void sqlite3VdbeTrace(Vdbe*,FILE);
+ //#endif
+ //void sqlite3VdbeResetStepResult(Vdbe);
+ //void sqlite3VdbeRewind(Vdbe);
+ //int sqlite3VdbeReset(Vdbe);
+ //void sqlite3VdbeSetNumCols(Vdbe*,int);
+ //int sqlite3VdbeSetColName(Vdbe*, int, int, string , void()(void));
+ //void sqlite3VdbeCountChanges(Vdbe);
+ //sqlite3 *sqlite3VdbeDb(Vdbe);
+ //void sqlite3VdbeSetSql(Vdbe*, string z, int n, int);
+ //void sqlite3VdbeSwap(Vdbe*,Vdbe);
+ //VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int);
+ //sqlite3_value *sqlite3VdbeGetValue(Vdbe*, int, u8);
+ //void sqlite3VdbeSetVarmask(Vdbe*, int);
+ //#if !SQLITE_OMIT_TRACE
+ // char *sqlite3VdbeExpandSql(Vdbe*, const char);
+ //#endif
- //UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
- //void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord);
- //int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord);
+ //UnpackedRecord *sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,char*,int);
+ //void sqlite3VdbeDeleteUnpackedRecord(UnpackedRecord);
+ //int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord);
- //#if !SQLITE_OMIT_TRIGGER
- //void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram );
- //#endif
+ //#if !SQLITE_OMIT_TRIGGER
+ //void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram );
+ //#endif
#if !NDEBUG
- //void sqlite3VdbeComment(Vdbe*, const char*, ...);
- static void VdbeComment( Vdbe v, string zFormat, params object[] ap )
- {
- sqlite3VdbeComment( v, zFormat, ap );
- }//# define VdbeComment(X) sqlite3VdbeComment X
- //void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
- static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap )
- {
- sqlite3VdbeNoopComment( v, zFormat, ap );
- }//# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
+ //void sqlite3VdbeComment(Vdbe*, const char*, ...);
+ static void VdbeComment(Vdbe v, string zFormat, params object[] ap) {
+ sqlite3VdbeComment(v, zFormat, ap);
+ }//# define VdbeComment(X) sqlite3VdbeComment X
+ //void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
+ static void VdbeNoopComment(Vdbe v, string zFormat, params object[] ap) {
+ sqlite3VdbeNoopComment(v, zFormat, ap);
+ }//# define VdbeNoopComment(X) sqlite3VdbeNoopComment X
#else
//# define VdbeComment(X)
static void VdbeComment( Vdbe v, string zFormat, params object[] ap ) { }
//# define VdbeNoopComment(X)
static void VdbeNoopComment( Vdbe v, string zFormat, params object[] ap ) { }
#endif
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/_Custom.cs b/Src/IronPython.SQLite/c#sqlite/_Custom.cs
index 06be9aa74..b0c0f7dc2 100644
--- a/Src/IronPython.SQLite/c#sqlite/_Custom.cs
+++ b/Src/IronPython.SQLite/c#sqlite/_Custom.cs
@@ -18,583 +18,483 @@
using u32 = System.UInt32;
using time_t = System.Int64;
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
+namespace Community.CsharpSqlite {
+ using sqlite3_value = Sqlite3.Mem;
- public partial class Sqlite3
- {
+ public partial class Sqlite3 {
-static int atoi( byte[] inStr )
-{
- return atoi( Encoding.UTF8.GetString( inStr, 0, inStr.Length ) );
-}
+ static int atoi(byte[] inStr) {
+ return atoi(Encoding.UTF8.GetString(inStr, 0, inStr.Length));
+ }
-static int atoi( string inStr )
-{
- int i;
- for ( i = 0; i < inStr.Length; i++ )
- {
- if ( !sqlite3Isdigit( inStr[i] ) && inStr[i] != '-' )
- break;
- }
- int result = 0;
-#if WINDOWS_MOBILE
+ static int atoi(string inStr) {
+ int i;
+ for (i = 0; i < inStr.Length; i++) {
+ if (!sqlite3Isdigit(inStr[i]) && inStr[i] != '-')
+ break;
+ }
+ int result = 0;
+#if WINDOWS_MOBILE
try { result = Int32.Parse(inStr.Substring(0, i)); }
catch { }
return result;
#else
- return ( Int32.TryParse( inStr.Substring( 0, i ), out result ) ? result : 0 );
+ return (Int32.TryParse(inStr.Substring(0, i), out result) ? result : 0);
#endif
-}
+ }
-static void fprintf( TextWriter tw, string zFormat, params object[] ap )
-{
- tw.Write( sqlite3_mprintf( zFormat, ap ) );
-}
-static void printf( string zFormat, params object[] ap )
-{
+ static void fprintf(TextWriter tw, string zFormat, params object[] ap) {
+ tw.Write(sqlite3_mprintf(zFormat, ap));
+ }
+ static void printf(string zFormat, params object[] ap) {
#if !SQLITE_WINRT
- Console.Out.Write( sqlite3_mprintf( zFormat, ap ) );
+ Console.Out.Write(sqlite3_mprintf(zFormat, ap));
#endif
-}
-
-
-//Byte Buffer Testing
-static int memcmp( byte[] bA, byte[] bB, int Limit )
-{
- if ( bA.Length < Limit )
- return ( bA.Length < bB.Length ) ? -1 : +1;
- if ( bB.Length < Limit )
- return +1;
- for ( int i = 0; i < Limit; i++ )
- {
- if ( bA[i] != bB[i] )
- return ( bA[i] < bB[i] ) ? -1 : 1;
- }
- return 0;
-}
+ }
-//Byte Buffer & String Testing
-static int memcmp( string A, byte[] bB, int Limit )
-{
- if ( A.Length < Limit )
- return ( A.Length < bB.Length ) ? -1 : +1;
- if ( bB.Length < Limit )
- return +1;
- char[] cA = A.ToCharArray();
- for ( int i = 0; i < Limit; i++ )
- {
- if ( cA[i] != bB[i] )
- return ( cA[i] < bB[i] ) ? -1 : 1;
- }
- return 0;
-}
-//byte with Offset & String Testing
-static int memcmp( byte[] a, int Offset, byte[] b, int Limit )
-{
- if ( a.Length < Offset + Limit )
- return ( a.Length - Offset < b.Length ) ? -1 : +1;
- if ( b.Length < Limit )
- return +1;
- for ( int i = 0; i < Limit; i++ )
- {
- if ( a[i + Offset] != b[i] )
- return ( a[i + Offset] < b[i] ) ? -1 : 1;
- }
- return 0;
-}
+ //Byte Buffer Testing
+ static int memcmp(byte[] bA, byte[] bB, int Limit) {
+ if (bA.Length < Limit)
+ return (bA.Length < bB.Length) ? -1 : +1;
+ if (bB.Length < Limit)
+ return +1;
+ for (int i = 0; i < Limit; i++) {
+ if (bA[i] != bB[i])
+ return (bA[i] < bB[i]) ? -1 : 1;
+ }
+ return 0;
+ }
-//byte with Offset & String Testing
-static int memcmp( byte[] a, int Aoffset, byte[] b, int Boffset, int Limit )
-{
- if ( a.Length < Aoffset + Limit )
- return ( a.Length - Aoffset < b.Length - Boffset ) ? -1 : +1;
- if ( b.Length < Boffset + Limit )
- return +1;
- for ( int i = 0; i < Limit; i++ )
- {
- if ( a[i + Aoffset] != b[i + Boffset] )
- return ( a[i + Aoffset] < b[i + Boffset] ) ? -1 : 1;
- }
- return 0;
-}
+ //Byte Buffer & String Testing
+ static int memcmp(string A, byte[] bB, int Limit) {
+ if (A.Length < Limit)
+ return (A.Length < bB.Length) ? -1 : +1;
+ if (bB.Length < Limit)
+ return +1;
+ char[] cA = A.ToCharArray();
+ for (int i = 0; i < Limit; i++) {
+ if (cA[i] != bB[i])
+ return (cA[i] < bB[i]) ? -1 : 1;
+ }
+ return 0;
+ }
-static int memcmp( byte[] a, int Offset, string b, int Limit )
-{
- if ( a.Length < Offset + Limit )
- return ( a.Length - Offset < b.Length ) ? -1 : +1;
- if ( b.Length < Limit )
- return +1;
- for ( int i = 0; i < Limit; i++ )
- {
- if ( a[i + Offset] != b[i] )
- return ( a[i + Offset] < b[i] ) ? -1 : 1;
- }
- return 0;
-}
-//String Testing
-static int memcmp( string A, string B, int Limit )
-{
- if ( A.Length < Limit )
- return ( A.Length < B.Length ) ? -1 : +1;
- if ( B.Length < Limit )
- return +1;
- int rc;
- if ( ( rc = String.Compare( A, 0, B, 0, Limit, StringComparison.Ordinal ) ) == 0 )
- return 0;
- return rc < 0 ? -1 : +1;
-}
+ //byte with Offset & String Testing
+ static int memcmp(byte[] a, int Offset, byte[] b, int Limit) {
+ if (a.Length < Offset + Limit)
+ return (a.Length - Offset < b.Length) ? -1 : +1;
+ if (b.Length < Limit)
+ return +1;
+ for (int i = 0; i < Limit; i++) {
+ if (a[i + Offset] != b[i])
+ return (a[i + Offset] < b[i]) ? -1 : 1;
+ }
+ return 0;
+ }
+ //byte with Offset & String Testing
+ static int memcmp(byte[] a, int Aoffset, byte[] b, int Boffset, int Limit) {
+ if (a.Length < Aoffset + Limit)
+ return (a.Length - Aoffset < b.Length - Boffset) ? -1 : +1;
+ if (b.Length < Boffset + Limit)
+ return +1;
+ for (int i = 0; i < Limit; i++) {
+ if (a[i + Aoffset] != b[i + Boffset])
+ return (a[i + Aoffset] < b[i + Boffset]) ? -1 : 1;
+ }
+ return 0;
+ }
-// ----------------------------
-// ** Builtin Functions
-// ----------------------------
+ static int memcmp(byte[] a, int Offset, string b, int Limit) {
+ if (a.Length < Offset + Limit)
+ return (a.Length - Offset < b.Length) ? -1 : +1;
+ if (b.Length < Limit)
+ return +1;
+ for (int i = 0; i < Limit; i++) {
+ if (a[i + Offset] != b[i])
+ return (a[i + Offset] < b[i]) ? -1 : 1;
+ }
+ return 0;
+ }
+ //String Testing
+ static int memcmp(string A, string B, int Limit) {
+ if (A.Length < Limit)
+ return (A.Length < B.Length) ? -1 : +1;
+ if (B.Length < Limit)
+ return +1;
+ int rc;
+ if ((rc = String.Compare(A, 0, B, 0, Limit, StringComparison.Ordinal)) == 0)
+ return 0;
+ return rc < 0 ? -1 : +1;
+ }
-static Regex oRegex = null;
-/*
-** The regexp() function. two arguments are both strings
-** Collating sequences are not used.
-*/
-static void regexpFunc(
-sqlite3_context context,
-int argc,
-sqlite3_value[] argv
-)
-{
- string zTest; /* The input string A */
- string zRegex; /* The regex string B */
-
- Debug.Assert( argc == 2 );
- UNUSED_PARAMETER( argc );
- zRegex = sqlite3_value_text( argv[0] );
- zTest = sqlite3_value_text( argv[1] );
-
- if ( zTest == null || String.IsNullOrEmpty( zRegex ) )
- {
- sqlite3_result_int( context, 0 );
- return;
- }
-
- if ( oRegex == null || oRegex.ToString() == zRegex )
- {
- oRegex = new Regex( zRegex, RegexOptions.IgnoreCase );
- }
- sqlite3_result_int( context, oRegex.IsMatch( zTest ) ? 1 : 0 );
-}
+ // ----------------------------
+ // ** Builtin Functions
+ // ----------------------------
+
+
+ static Regex oRegex = null;
+ /*
+ ** The regexp() function. two arguments are both strings
+ ** Collating sequences are not used.
+ */
+ static void regexpFunc(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
+ string zTest; /* The input string A */
+ string zRegex; /* The regex string B */
+
+ Debug.Assert(argc == 2);
+ UNUSED_PARAMETER(argc);
+ zRegex = sqlite3_value_text(argv[0]);
+ zTest = sqlite3_value_text(argv[1]);
+
+ if (zTest == null || String.IsNullOrEmpty(zRegex)) {
+ sqlite3_result_int(context, 0);
+ return;
+ }
+
+ if (oRegex == null || oRegex.ToString() == zRegex) {
+ oRegex = new Regex(zRegex, RegexOptions.IgnoreCase);
+ }
+ sqlite3_result_int(context, oRegex.IsMatch(zTest) ? 1 : 0);
+ }
-// ----------------------------
-// ** Convertion routines
-// ----------------------------
-static Object lock_va_list = new Object();
+ // ----------------------------
+ // ** Convertion routines
+ // ----------------------------
+ static Object lock_va_list = new Object();
-static string vaFORMAT;
-static int vaNEXT;
+ static string vaFORMAT;
+ static int vaNEXT;
-static void va_start( object[] ap, string zFormat )
-{
- vaFORMAT = zFormat;
- vaNEXT = 0;
-}
+ static void va_start(object[] ap, string zFormat) {
+ vaFORMAT = zFormat;
+ vaNEXT = 0;
+ }
-static Boolean va_arg( object[] ap, Boolean sysType )
-{
- return Convert.ToBoolean( ap[vaNEXT++] );
-}
+ static Boolean va_arg(object[] ap, Boolean sysType) {
+ return Convert.ToBoolean(ap[vaNEXT++]);
+ }
-static Byte[] va_arg( object[] ap, Byte[] sysType )
-{
- return (Byte[])ap[vaNEXT++];
-}
+ static Byte[] va_arg(object[] ap, Byte[] sysType) {
+ return (Byte[])ap[vaNEXT++];
+ }
-static Byte[][] va_arg( object[] ap, Byte[][] sysType )
-{
- if ( ap[vaNEXT] == null )
- {
- {
- vaNEXT++;
- return null;
- }
- }
- else
- {
- return (Byte[][])ap[vaNEXT++];
- }
-}
+ static Byte[][] va_arg(object[] ap, Byte[][] sysType) {
+ if (ap[vaNEXT] == null) {
+ {
+ vaNEXT++;
+ return null;
+ }
+ } else {
+ return (Byte[][])ap[vaNEXT++];
+ }
+ }
-static Char va_arg( object[] ap, Char sysType )
-{
- if ( ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0 )
- {
- vaNEXT++;
- return (char)'0';
- }
- else
- {
- if ( ap[vaNEXT] is Int64 )
- if ( (i64)ap[vaNEXT] == 0 )
- {
- vaNEXT++;
- return (char)'0';
- }
- else
- return (char)( (i64)ap[vaNEXT++] );
- else
- return (char)ap[vaNEXT++];
- }
+ static Char va_arg(object[] ap, Char sysType) {
+ if (ap[vaNEXT] is Int32 && (int)ap[vaNEXT] == 0) {
+ vaNEXT++;
+ return (char)'0';
+ } else {
+ if (ap[vaNEXT] is Int64)
+ if ((i64)ap[vaNEXT] == 0) {
+ vaNEXT++;
+ return (char)'0';
+ } else
+ return (char)((i64)ap[vaNEXT++]);
+ else
+ return (char)ap[vaNEXT++];
+ }
-}
+ }
-static Double va_arg( object[] ap, Double sysType )
-{
- return Convert.ToDouble( ap[vaNEXT++] );
-}
+ static Double va_arg(object[] ap, Double sysType) {
+ return Convert.ToDouble(ap[vaNEXT++]);
+ }
-static dxLog va_arg( object[] ap, dxLog sysType )
-{
- return (dxLog)ap[vaNEXT++];
-}
+ static dxLog va_arg(object[] ap, dxLog sysType) {
+ return (dxLog)ap[vaNEXT++];
+ }
-static Int64 va_arg( object[] ap, Int64 sysType )
-{
- if ( ap[vaNEXT] is System.Int64)
- return Convert.ToInt64( ap[vaNEXT++] );
- else
- return (Int64)( ap[vaNEXT++].GetHashCode() );
-}
+ static Int64 va_arg(object[] ap, Int64 sysType) {
+ if (ap[vaNEXT] is System.Int64)
+ return Convert.ToInt64(ap[vaNEXT++]);
+ else
+ return (Int64)(ap[vaNEXT++].GetHashCode());
+ }
-static Int32 va_arg( object[] ap, Int32 sysType )
-{
- if ( Convert.ToInt64( ap[vaNEXT] ) > 0 && ( Convert.ToUInt32( ap[vaNEXT] ) > Int32.MaxValue ) )
- return (Int32)( Convert.ToUInt32( ap[vaNEXT++] ) - System.UInt32.MaxValue - 1 );
- else
- return (Int32)Convert.ToInt32( ap[vaNEXT++] );
-}
+ static Int32 va_arg(object[] ap, Int32 sysType) {
+ if (Convert.ToInt64(ap[vaNEXT]) > 0 && (Convert.ToUInt32(ap[vaNEXT]) > Int32.MaxValue))
+ return (Int32)(Convert.ToUInt32(ap[vaNEXT++]) - System.UInt32.MaxValue - 1);
+ else
+ return (Int32)Convert.ToInt32(ap[vaNEXT++]);
+ }
-static Int32[] va_arg( object[] ap, Int32[] sysType )
-{
- if ( ap[vaNEXT] == null )
- {
- {
- vaNEXT++;
- return null;
- }
- }
- else
- {
- return (Int32[])ap[vaNEXT++];
- }
-}
+ static Int32[] va_arg(object[] ap, Int32[] sysType) {
+ if (ap[vaNEXT] == null) {
+ {
+ vaNEXT++;
+ return null;
+ }
+ } else {
+ return (Int32[])ap[vaNEXT++];
+ }
+ }
-static MemPage va_arg( object[] ap, MemPage sysType )
-{
- return (MemPage)ap[vaNEXT++];
-}
+ static MemPage va_arg(object[] ap, MemPage sysType) {
+ return (MemPage)ap[vaNEXT++];
+ }
-static Object va_arg( object[] ap, Object sysType )
-{
- return (Object)ap[vaNEXT++];
-}
+ static Object va_arg(object[] ap, Object sysType) {
+ return (Object)ap[vaNEXT++];
+ }
-static sqlite3 va_arg( object[] ap, sqlite3 sysType )
-{
- return (sqlite3)ap[vaNEXT++];
-}
+ static sqlite3 va_arg(object[] ap, sqlite3 sysType) {
+ return (sqlite3)ap[vaNEXT++];
+ }
-static sqlite3_mem_methods va_arg( object[] ap, sqlite3_mem_methods sysType )
-{
- return (sqlite3_mem_methods)ap[vaNEXT++];
-}
+ static sqlite3_mem_methods va_arg(object[] ap, sqlite3_mem_methods sysType) {
+ return (sqlite3_mem_methods)ap[vaNEXT++];
+ }
-static sqlite3_mutex_methods va_arg( object[] ap, sqlite3_mutex_methods sysType )
-{
- return (sqlite3_mutex_methods)ap[vaNEXT++];
-}
+ static sqlite3_mutex_methods va_arg(object[] ap, sqlite3_mutex_methods sysType) {
+ return (sqlite3_mutex_methods)ap[vaNEXT++];
+ }
-static SrcList va_arg( object[] ap, SrcList sysType )
-{
- return (SrcList)ap[vaNEXT++];
-}
+ static SrcList va_arg(object[] ap, SrcList sysType) {
+ return (SrcList)ap[vaNEXT++];
+ }
-static String va_arg( object[] ap, String sysType )
-{
- if ( ap.Length < vaNEXT - 1 || ap[vaNEXT] == null )
- {
- vaNEXT++;
- return "NULL";
- }
- else
- {
- if ( ap[vaNEXT] is Byte[] )
- if ( Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT] ).Length ) == "\0" )
- {
- vaNEXT++;
- return "";
- }
- else
- return Encoding.UTF8.GetString( (byte[])ap[vaNEXT], 0, ( (byte[])ap[vaNEXT++] ).Length );
- else if ( ap[vaNEXT] is Int32 )
- {
- vaNEXT++;
- return null;
- }
- else if ( ap[vaNEXT] is StringBuilder )
- return (String)ap[vaNEXT++].ToString();
- else if ( ap[vaNEXT] is Char )
- return ( (Char)ap[vaNEXT++] ).ToString();
- else
- return (String)ap[vaNEXT++];
- }
-}
+ static String va_arg(object[] ap, String sysType) {
+ if (ap.Length < vaNEXT - 1 || ap[vaNEXT] == null) {
+ vaNEXT++;
+ return "NULL";
+ } else {
+ if (ap[vaNEXT] is Byte[])
+ if (Encoding.UTF8.GetString((byte[])ap[vaNEXT], 0, ((byte[])ap[vaNEXT]).Length) == "\0") {
+ vaNEXT++;
+ return "";
+ } else
+ return Encoding.UTF8.GetString((byte[])ap[vaNEXT], 0, ((byte[])ap[vaNEXT++]).Length);
+ else if (ap[vaNEXT] is Int32) {
+ vaNEXT++;
+ return null;
+ } else if (ap[vaNEXT] is StringBuilder)
+ return (String)ap[vaNEXT++].ToString();
+ else if (ap[vaNEXT] is Char)
+ return ((Char)ap[vaNEXT++]).ToString();
+ else
+ return (String)ap[vaNEXT++];
+ }
+ }
-static Token va_arg( object[] ap, Token sysType )
-{
- return (Token)ap[vaNEXT++];
-}
+ static Token va_arg(object[] ap, Token sysType) {
+ return (Token)ap[vaNEXT++];
+ }
-static UInt32 va_arg( object[] ap, UInt32 sysType )
-{
+ static UInt32 va_arg(object[] ap, UInt32 sysType) {
#if SQLITE_WINRT
Type t = ap[vaNEXT].GetType();
if ( t.IsClass )
#else
- if ( ap[vaNEXT].GetType().IsClass )
+ if (ap[vaNEXT].GetType().IsClass)
#endif
- {
- return (UInt32)ap[vaNEXT++].GetHashCode();
- }
- else
- {
- return (UInt32)Convert.ToUInt32( ap[vaNEXT++] );
- }
-}
+ {
+ return (UInt32)ap[vaNEXT++].GetHashCode();
+ } else {
+ return (UInt32)Convert.ToUInt32(ap[vaNEXT++]);
+ }
+ }
-static UInt64 va_arg( object[] ap, UInt64 sysType )
-{
+ static UInt64 va_arg(object[] ap, UInt64 sysType) {
#if SQLITE_WINRT
Type t = ap[vaNEXT].GetType();
if (t.IsClass)
#else
- if ( ap[vaNEXT].GetType().IsClass )
+ if (ap[vaNEXT].GetType().IsClass)
#endif
- {
- return (UInt64)ap[vaNEXT++].GetHashCode();
- }
- else
- {
- return (UInt64)Convert.ToUInt64( ap[vaNEXT++] );
- }
-}
-
-static void_function va_arg( object[] ap, void_function sysType )
-{
- return (void_function)ap[vaNEXT++];
-}
+ {
+ return (UInt64)ap[vaNEXT++].GetHashCode();
+ } else {
+ return (UInt64)Convert.ToUInt64(ap[vaNEXT++]);
+ }
+ }
+ static void_function va_arg(object[] ap, void_function sysType) {
+ return (void_function)ap[vaNEXT++];
+ }
-static void va_end( ref string[] ap )
-{
- ap = null;
- vaNEXT = -1;
- vaFORMAT = "";
-}
-static void va_end( ref object[] ap )
-{
- ap = null;
- vaNEXT = -1;
- vaFORMAT = "";
-}
+ static void va_end(ref string[] ap) {
+ ap = null;
+ vaNEXT = -1;
+ vaFORMAT = "";
+ }
+ static void va_end(ref object[] ap) {
+ ap = null;
+ vaNEXT = -1;
+ vaFORMAT = "";
+ }
-public static tm localtime( time_t baseTime )
-{
- System.DateTime RefTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
- RefTime = RefTime.AddSeconds( Convert.ToDouble( baseTime ) ).ToLocalTime();
- tm tm = new tm();
- tm.tm_sec = RefTime.Second;
- tm.tm_min = RefTime.Minute;
- tm.tm_hour = RefTime.Hour;
- tm.tm_mday = RefTime.Day;
- tm.tm_mon = RefTime.Month;
- tm.tm_year = RefTime.Year;
- tm.tm_wday = (int)RefTime.DayOfWeek;
- tm.tm_yday = RefTime.DayOfYear;
- tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0;
- return tm;
-}
-public static long ToUnixtime( System.DateTime date )
-{
- System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
- System.TimeSpan timeSpan = date - unixStartTime;
- return Convert.ToInt64( timeSpan.TotalSeconds );
-}
+ public static tm localtime(time_t baseTime) {
+ System.DateTime RefTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
+ RefTime = RefTime.AddSeconds(Convert.ToDouble(baseTime)).ToLocalTime();
+ tm tm = new tm();
+ tm.tm_sec = RefTime.Second;
+ tm.tm_min = RefTime.Minute;
+ tm.tm_hour = RefTime.Hour;
+ tm.tm_mday = RefTime.Day;
+ tm.tm_mon = RefTime.Month;
+ tm.tm_year = RefTime.Year;
+ tm.tm_wday = (int)RefTime.DayOfWeek;
+ tm.tm_yday = RefTime.DayOfYear;
+ tm.tm_isdst = RefTime.IsDaylightSavingTime() ? 1 : 0;
+ return tm;
+ }
-public static System.DateTime ToCSharpTime( long unixTime )
-{
- System.DateTime unixStartTime = new System.DateTime( 1970, 1, 1, 0, 0, 0, 0 );
- return unixStartTime.AddSeconds( Convert.ToDouble( unixTime ) );
-}
+ public static long ToUnixtime(System.DateTime date) {
+ System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
+ System.TimeSpan timeSpan = date - unixStartTime;
+ return Convert.ToInt64(timeSpan.TotalSeconds);
+ }
-public class tm
-{
- public int tm_sec; /* seconds after the minute - [0,59] */
- public int tm_min; /* minutes after the hour - [0,59] */
- public int tm_hour; /* hours since midnight - [0,23] */
- public int tm_mday; /* day of the month - [1,31] */
- public int tm_mon; /* months since January - [0,11] */
- public int tm_year; /* years since 1900 */
- public int tm_wday; /* days since Sunday - [0,6] */
- public int tm_yday; /* days since January 1 - [0,365] */
- public int tm_isdst; /* daylight savings time flag */
-};
+ public static System.DateTime ToCSharpTime(long unixTime) {
+ System.DateTime unixStartTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
+ return unixStartTime.AddSeconds(Convert.ToDouble(unixTime));
+ }
-public struct FILETIME
-{
- public u32 dwLowDateTime;
- public u32 dwHighDateTime;
-}
+ public class tm {
+ public int tm_sec; /* seconds after the minute - [0,59] */
+ public int tm_min; /* minutes after the hour - [0,59] */
+ public int tm_hour; /* hours since midnight - [0,23] */
+ public int tm_mday; /* day of the month - [1,31] */
+ public int tm_mon; /* months since January - [0,11] */
+ public int tm_year; /* years since 1900 */
+ public int tm_wday; /* days since Sunday - [0,6] */
+ public int tm_yday; /* days since January 1 - [0,365] */
+ public int tm_isdst; /* daylight savings time flag */
+ };
+
+ public struct FILETIME {
+ public u32 dwLowDateTime;
+ public u32 dwHighDateTime;
+ }
-static void SWAP( ref T A, ref T B )
-{
- T t = A;
- A = B;
- B = t;
-}
+ static void SWAP(ref T A, ref T B) {
+ T t = A;
+ A = B;
+ B = t;
+ }
-static void x_CountStep(
-sqlite3_context context,
-int argc,
-sqlite3_value[] argv
-)
-{
- SumCtx p;
-
- int type;
- Debug.Assert( argc <= 1 );
- Mem pMem = sqlite3_aggregate_context( context, 1 );//sizeof(*p));
- if ( pMem._SumCtx == null )
- pMem._SumCtx = new SumCtx();
- p = pMem._SumCtx;
- if ( p.Context == null )
- p.Context = pMem;
- if ( argc == 0 || SQLITE_NULL == sqlite3_value_type( argv[0] ) )
- {
- p.cnt++;
- p.iSum += 1;
- }
- else
- {
- type = sqlite3_value_numeric_type( argv[0] );
- if ( p != null && type != SQLITE_NULL )
- {
- p.cnt++;
- if ( type == SQLITE_INTEGER )
- {
- i64 v = sqlite3_value_int64( argv[0] );
- if ( v == 40 || v == 41 )
- {
- sqlite3_result_error( context, "value of " + v + " handed to x_count", -1 );
- return;
- }
- else
- {
- p.iSum += v;
- if ( !( p.approx | p.overflow != 0 ) )
- {
- i64 iNewSum = p.iSum + v;
- int s1 = (int)( p.iSum >> ( sizeof( i64 ) * 8 - 1 ) );
- int s2 = (int)( v >> ( sizeof( i64 ) * 8 - 1 ) );
- int s3 = (int)( iNewSum >> ( sizeof( i64 ) * 8 - 1 ) );
- p.overflow = ( ( s1 & s2 & ~s3 ) | ( ~s1 & ~s2 & s3 ) ) != 0 ? 1 : 0;
- p.iSum = iNewSum;
- }
- }
- }
- else
- {
- p.rSum += sqlite3_value_double( argv[0] );
- p.approx = true;
- }
- }
- }
-}
-static void x_CountFinalize( sqlite3_context context )
-{
- SumCtx p;
- Mem pMem = sqlite3_aggregate_context( context, 0 );
- p = pMem._SumCtx;
- if ( p != null && p.cnt > 0 )
- {
- if ( p.overflow != 0 )
- {
- sqlite3_result_error( context, "integer overflow", -1 );
- }
- else if ( p.approx )
- {
- sqlite3_result_double( context, p.rSum );
- }
- else if ( p.iSum == 42 )
- {
- sqlite3_result_error( context, "x_count totals to 42", -1 );
- }
- else
- {
- sqlite3_result_int64( context, p.iSum );
- }
- }
-}
+ static void x_CountStep(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
+ SumCtx p;
+
+ int type;
+ Debug.Assert(argc <= 1);
+ Mem pMem = sqlite3_aggregate_context(context, 1);//sizeof(*p));
+ if (pMem._SumCtx == null)
+ pMem._SumCtx = new SumCtx();
+ p = pMem._SumCtx;
+ if (p.Context == null)
+ p.Context = pMem;
+ if (argc == 0 || SQLITE_NULL == sqlite3_value_type(argv[0])) {
+ p.cnt++;
+ p.iSum += 1;
+ } else {
+ type = sqlite3_value_numeric_type(argv[0]);
+ if (p != null && type != SQLITE_NULL) {
+ p.cnt++;
+ if (type == SQLITE_INTEGER) {
+ i64 v = sqlite3_value_int64(argv[0]);
+ if (v == 40 || v == 41) {
+ sqlite3_result_error(context, "value of " + v + " handed to x_count", -1);
+ return;
+ } else {
+ p.iSum += v;
+ if (!(p.approx | p.overflow != 0)) {
+ i64 iNewSum = p.iSum + v;
+ int s1 = (int)(p.iSum >> (sizeof(i64) * 8 - 1));
+ int s2 = (int)(v >> (sizeof(i64) * 8 - 1));
+ int s3 = (int)(iNewSum >> (sizeof(i64) * 8 - 1));
+ p.overflow = ((s1 & s2 & ~s3) | (~s1 & ~s2 & s3)) != 0 ? 1 : 0;
+ p.iSum = iNewSum;
+ }
+ }
+ } else {
+ p.rSum += sqlite3_value_double(argv[0]);
+ p.approx = true;
+ }
+ }
+ }
+ }
+ static void x_CountFinalize(sqlite3_context context) {
+ SumCtx p;
+ Mem pMem = sqlite3_aggregate_context(context, 0);
+ p = pMem._SumCtx;
+ if (p != null && p.cnt > 0) {
+ if (p.overflow != 0) {
+ sqlite3_result_error(context, "integer overflow", -1);
+ } else if (p.approx) {
+ sqlite3_result_double(context, p.rSum);
+ } else if (p.iSum == 42) {
+ sqlite3_result_error(context, "x_count totals to 42", -1);
+ } else {
+ sqlite3_result_int64(context, p.iSum);
+ }
+ }
+ }
#if SQLITE_MUTEX_W32
-//---------------------WIN32 Definitions
-static int GetCurrentThreadId()
-{
- return Environment.CurrentManagedThreadId;
-}
-static long InterlockedIncrement( long location )
-{
- Interlocked.Increment( ref location );
- return location;
-}
-static void EnterCriticalSection( Object mtx )
-{
- //long mid = mtx.GetHashCode();
- //int tid = Thread.CurrentThread.ManagedThreadId;
- //long ticks = cnt++;
- //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) );
- Monitor.Enter( mtx );
-}
-static void InitializeCriticalSection( Object mtx )
-{
- //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks ));
-}
-static void DeleteCriticalSection( Object mtx )
-{
- //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) );
-}
-static void LeaveCriticalSection( Object mtx )
-{
- //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks ));
- Monitor.Exit( mtx );
-}
+ //---------------------WIN32 Definitions
+ static int GetCurrentThreadId() {
+ return Environment.CurrentManagedThreadId;
+ }
+ static long InterlockedIncrement(long location) {
+ Interlocked.Increment(ref location);
+ return location;
+ }
+ static void EnterCriticalSection(Object mtx) {
+ //long mid = mtx.GetHashCode();
+ //int tid = Thread.CurrentThread.ManagedThreadId;
+ //long ticks = cnt++;
+ //Debug.WriteLine(String.Format( "{2}: +EnterCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, ticks) );
+ Monitor.Enter(mtx);
+ }
+ static void InitializeCriticalSection(Object mtx) {
+ //Debug.WriteLine(String.Format( "{2}: +InitializeCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks ));
+ }
+ static void DeleteCriticalSection(Object mtx) {
+ //Debug.WriteLine(String.Format( "{2}: +DeleteCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks) );
+ }
+ static void LeaveCriticalSection(Object mtx) {
+ //Debug.WriteLine(String.Format("{2}: +LeaveCriticalSection; Mutex {0} Thread {1}", mtx.GetHashCode(), Thread.CurrentThread.ManagedThreadId, System.DateTime.Now.Ticks ));
+ Monitor.Exit(mtx);
+ }
#endif
-// Miscellaneous Windows Constants
-//#define ERROR_FILE_NOT_FOUND 2L
-//#define ERROR_HANDLE_DISK_FULL 39L
-//#define ERROR_NOT_SUPPORTED 50L
-//#define ERROR_DISK_FULL 112L
-const long ERROR_FILE_NOT_FOUND = 2L;
-const long ERROR_HANDLE_DISK_FULL = 39L;
-const long ERROR_NOT_SUPPORTED = 50L;
-const long ERROR_DISK_FULL = 112L;
-
-private class SQLite3UpperToLower
-{
- static int[] sqlite3UpperToLower = new int[] {
+ // Miscellaneous Windows Constants
+ //#define ERROR_FILE_NOT_FOUND 2L
+ //#define ERROR_HANDLE_DISK_FULL 39L
+ //#define ERROR_NOT_SUPPORTED 50L
+ //#define ERROR_DISK_FULL 112L
+ const long ERROR_FILE_NOT_FOUND = 2L;
+ const long ERROR_HANDLE_DISK_FULL = 39L;
+ const long ERROR_NOT_SUPPORTED = 50L;
+ const long ERROR_DISK_FULL = 112L;
+
+ private class SQLite3UpperToLower {
+ static int[] sqlite3UpperToLower = new int[] {
#if SQLITE_ASCII
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
@@ -613,31 +513,27 @@ private class SQLite3UpperToLower
252,253,254,255
#endif
};
- public int this[int index]
- {
- get
- {
- if ( index < sqlite3UpperToLower.Length )
- return sqlite3UpperToLower[index];
- else
- return index;
- }
- }
-
- public int this[u32 index]
- {
- get
- {
- if ( index < sqlite3UpperToLower.Length )
- return sqlite3UpperToLower[index];
- else
- return (int)index;
- }
- }
-}
+ public int this[int index] {
+ get {
+ if (index < sqlite3UpperToLower.Length)
+ return sqlite3UpperToLower[index];
+ else
+ return index;
+ }
+ }
+
+ public int this[u32 index] {
+ get {
+ if (index < sqlite3UpperToLower.Length)
+ return sqlite3UpperToLower[index];
+ else
+ return (int)index;
+ }
+ }
+ }
-static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower();
-static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower;
+ static SQLite3UpperToLower sqlite3UpperToLower = new SQLite3UpperToLower();
+ static SQLite3UpperToLower UpperToLower = sqlite3UpperToLower;
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/alter_c.cs b/Src/IronPython.SQLite/c#sqlite/alter_c.cs
index d2147ab74..f1eb50e99 100644
--- a/Src/IronPython.SQLite/c#sqlite/alter_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/alter_c.cs
@@ -1,278 +1,259 @@
using System;
using System.Diagnostics;
-using System.Text;
-
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
-
- public partial class Sqlite3
- {
-/*
-** 2005 February 15
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains C code routines that used to generate VDBE code
-** that implements the ALTER TABLE command.
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
-**
-*************************************************************************
-*/
-//#include "sqliteInt.h"
-
-/*
-** The code in this file only exists if we are not omitting the
-** ALTER TABLE logic from the build.
-*/
-#if !SQLITE_OMIT_ALTERTABLE
+namespace Community.CsharpSqlite {
+ using sqlite3_value = Sqlite3.Mem;
+
+ public partial class Sqlite3 {
+ /*
+ ** 2005 February 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains C code routines that used to generate VDBE code
+ ** that implements the ALTER TABLE command.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
+
+ /*
+ ** The code in this file only exists if we are not omitting the
+ ** ALTER TABLE logic from the build.
+ */
+#if !SQLITE_OMIT_ALTERTABLE
-/*
-** This function is used by SQL generated to implement the
-** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
-** CREATE INDEX command. The second is a table name. The table name in
-** the CREATE TABLE or CREATE INDEX statement is replaced with the third
-** argument and the result returned. Examples:
-**
-** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
-** . 'CREATE TABLE def(a, b, c)'
-**
-** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
-** . 'CREATE INDEX i ON def(a, b, c)'
-*/
-static void renameTableFunc(
-sqlite3_context context,
-int NotUsed,
-sqlite3_value[] argv
-)
-{
- string bResult = sqlite3_value_text( argv[0] );
- string zSql = bResult == null ? "" : bResult;
- string zTableName = sqlite3_value_text( argv[1] );
-
- int token = 0;
- Token tname = new Token();
- int zCsr = 0;
- int zLoc = 0;
- int len = 0;
- string zRet;
-
- sqlite3 db = sqlite3_context_db_handle( context );
-
- UNUSED_PARAMETER( NotUsed );
-
- /* The principle used to locate the table name in the CREATE TABLE
- ** statement is that the table name is the first non-space token that
- ** is immediately followed by a TK_LP or TK_USING token.
- */
- if ( zSql != "" )
- {
- do
- {
- if ( zCsr == zSql.Length )
- {
- /* Ran out of input before finding an opening bracket. Return NULL. */
- return;
- }
-
- /* Store the token that zCsr points to in tname. */
- zLoc = zCsr;
- tname.z = zSql.Substring( zCsr );//(char*)zCsr;
- tname.n = len;
-
- /* Advance zCsr to the next token. Store that token type in 'token',
- ** and its length in 'len' (to be used next iteration of this loop).
- */
- do
- {
- zCsr += len;
- len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token );
- } while ( token == TK_SPACE );
- Debug.Assert( len > 0 );
- } while ( token != TK_LP && token != TK_USING );
-
- zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ),
- zTableName, zSql.Substring( zLoc + tname.n ) );
-
- sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC );
- }
-}
-/*
-** This C function implements an SQL user function that is used by SQL code
-** generated by the ALTER TABLE ... RENAME command to modify the definition
-** of any foreign key constraints that use the table being renamed as the
-** parent table. It is passed three arguments:
-**
-** 1) The complete text of the CREATE TABLE statement being modified,
-** 2) The old name of the table being renamed, and
-** 3) The new name of the table being renamed.
-**
-** It returns the new CREATE TABLE statement. For example:
-**
-** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
-** -> 'CREATE TABLE t1(a REFERENCES t3)'
-*/
+ /*
+ ** This function is used by SQL generated to implement the
+ ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
+ ** CREATE INDEX command. The second is a table name. The table name in
+ ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
+ ** argument and the result returned. Examples:
+ **
+ ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
+ ** . 'CREATE TABLE def(a, b, c)'
+ **
+ ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
+ ** . 'CREATE INDEX i ON def(a, b, c)'
+ */
+ static void renameTableFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] argv
+ ) {
+ string bResult = sqlite3_value_text(argv[0]);
+ string zSql = bResult == null ? "" : bResult;
+ string zTableName = sqlite3_value_text(argv[1]);
+
+ int token = 0;
+ Token tname = new Token();
+ int zCsr = 0;
+ int zLoc = 0;
+ int len = 0;
+ string zRet;
+
+ sqlite3 db = sqlite3_context_db_handle(context);
+
+ UNUSED_PARAMETER(NotUsed);
+
+ /* The principle used to locate the table name in the CREATE TABLE
+ ** statement is that the table name is the first non-space token that
+ ** is immediately followed by a TK_LP or TK_USING token.
+ */
+ if (zSql != "") {
+ do {
+ if (zCsr == zSql.Length) {
+ /* Ran out of input before finding an opening bracket. Return NULL. */
+ return;
+ }
+
+ /* Store the token that zCsr points to in tname. */
+ zLoc = zCsr;
+ tname.z = zSql.Substring(zCsr);//(char*)zCsr;
+ tname.n = len;
+
+ /* Advance zCsr to the next token. Store that token type in 'token',
+ ** and its length in 'len' (to be used next iteration of this loop).
+ */
+ do {
+ zCsr += len;
+ len = (zCsr == zSql.Length) ? 1 : sqlite3GetToken(zSql, zCsr, ref token);
+ } while (token == TK_SPACE);
+ Debug.Assert(len > 0);
+ } while (token != TK_LP && token != TK_USING);
+
+ zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", zLoc, zSql.Substring(0, zLoc),
+ zTableName, zSql.Substring(zLoc + tname.n));
+
+ sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
+ }
+ }
+
+ /*
+ ** This C function implements an SQL user function that is used by SQL code
+ ** generated by the ALTER TABLE ... RENAME command to modify the definition
+ ** of any foreign key constraints that use the table being renamed as the
+ ** parent table. It is passed three arguments:
+ **
+ ** 1) The complete text of the CREATE TABLE statement being modified,
+ ** 2) The old name of the table being renamed, and
+ ** 3) The new name of the table being renamed.
+ **
+ ** It returns the new CREATE TABLE statement. For example:
+ **
+ ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
+ ** -> 'CREATE TABLE t1(a REFERENCES t3)'
+ */
#if !SQLITE_OMIT_FOREIGN_KEY
-static void renameParentFunc(
- sqlite3_context context,
- int NotUsed,
- sqlite3_value[] argv
-)
-{
- sqlite3 db = sqlite3_context_db_handle( context );
- string zOutput = "";
- string zResult;
- string zInput = sqlite3_value_text( argv[0] );
- string zOld = sqlite3_value_text( argv[1] );
- string zNew = sqlite3_value_text( argv[2] );
-
- int zIdx; /* Pointer to token */
- int zLeft = 0; /* Pointer to remainder of String */
- int n = 0; /* Length of token z */
- int token = 0; /* Type of token */
-
- UNUSED_PARAMETER( NotUsed );
- for ( zIdx = 0; zIdx < zInput.Length; zIdx += n )//z=zInput; *z; z=z+n)
- {
- n = sqlite3GetToken( zInput, zIdx, ref token );
- if ( token == TK_REFERENCES )
- {
- string zParent;
- do
- {
- zIdx += n;
- n = sqlite3GetToken( zInput, zIdx, ref token );
- } while ( token == TK_SPACE );
-
- zParent = zIdx + n < zInput.Length ? zInput.Substring( zIdx, n ) : "";//sqlite3DbStrNDup(db, zIdx, n);
- if ( String.IsNullOrEmpty( zParent ) )
- break;
- sqlite3Dequote( ref zParent );
- if ( zOld.Equals( zParent, StringComparison.OrdinalIgnoreCase) )
- {
- string zOut = sqlite3MPrintf( db, "%s%.*s\"%w\"",
- zOutput, zIdx - zLeft, zInput.Substring( zLeft ), zNew
- );
- sqlite3DbFree( db, ref zOutput );
- zOutput = zOut;
- zIdx += n;// zInput = &z[n];
- zLeft = zIdx;
- }
- sqlite3DbFree( db, ref zParent );
- }
- }
-
- zResult = sqlite3MPrintf( db, "%s%s", zOutput, zInput.Substring( zLeft ) );
- sqlite3_result_text( context, zResult, -1, SQLITE_DYNAMIC );
- sqlite3DbFree( db, ref zOutput );
-}
+ static void renameParentFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] argv
+ ) {
+ sqlite3 db = sqlite3_context_db_handle(context);
+ string zOutput = "";
+ string zResult;
+ string zInput = sqlite3_value_text(argv[0]);
+ string zOld = sqlite3_value_text(argv[1]);
+ string zNew = sqlite3_value_text(argv[2]);
+
+ int zIdx; /* Pointer to token */
+ int zLeft = 0; /* Pointer to remainder of String */
+ int n = 0; /* Length of token z */
+ int token = 0; /* Type of token */
+
+ UNUSED_PARAMETER(NotUsed);
+ for (zIdx = 0; zIdx < zInput.Length; zIdx += n)//z=zInput; *z; z=z+n)
+ {
+ n = sqlite3GetToken(zInput, zIdx, ref token);
+ if (token == TK_REFERENCES) {
+ string zParent;
+ do {
+ zIdx += n;
+ n = sqlite3GetToken(zInput, zIdx, ref token);
+ } while (token == TK_SPACE);
+
+ zParent = zIdx + n < zInput.Length ? zInput.Substring(zIdx, n) : "";//sqlite3DbStrNDup(db, zIdx, n);
+ if (String.IsNullOrEmpty(zParent))
+ break;
+ sqlite3Dequote(ref zParent);
+ if (zOld.Equals(zParent, StringComparison.OrdinalIgnoreCase)) {
+ string zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
+ zOutput, zIdx - zLeft, zInput.Substring(zLeft), zNew
+ );
+ sqlite3DbFree(db, ref zOutput);
+ zOutput = zOut;
+ zIdx += n;// zInput = &z[n];
+ zLeft = zIdx;
+ }
+ sqlite3DbFree(db, ref zParent);
+ }
+ }
+
+ zResult = sqlite3MPrintf(db, "%s%s", zOutput, zInput.Substring(zLeft));
+ sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
+ sqlite3DbFree(db, ref zOutput);
+ }
#endif
#if !SQLITE_OMIT_TRIGGER
-/* This function is used by SQL generated to implement the
-** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
-** statement. The second is a table name. The table name in the CREATE
-** TRIGGER statement is replaced with the third argument and the result
-** returned. This is analagous to renameTableFunc() above, except for CREATE
-** TRIGGER, not CREATE INDEX and CREATE TABLE.
-*/
-static void renameTriggerFunc(
-sqlite3_context context,
-int NotUsed,
-sqlite3_value[] argv
-)
-{
- string zSql = sqlite3_value_text( argv[0] );
- string zTableName = sqlite3_value_text( argv[1] );
-
- int token = 0;
- Token tname = new Token();
- int dist = 3;
- int zCsr = 0;
- int zLoc = 0;
- int len = 1;
- string zRet;
-
- sqlite3 db = sqlite3_context_db_handle( context );
-
- UNUSED_PARAMETER( NotUsed );
-
- /* The principle used to locate the table name in the CREATE TRIGGER
- ** statement is that the table name is the first token that is immediatedly
- ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
- ** of TK_WHEN, TK_BEGIN or TK_FOR.
- */
- if ( zSql != null )
- {
- do
- {
-
- if ( zCsr == zSql.Length )
- {
- /* Ran out of input before finding the table name. Return NULL. */
- return;
- }
-
- /* Store the token that zCsr points to in tname. */
- zLoc = zCsr;
- tname.z = zSql.Substring( zCsr, len );//(char*)zCsr;
- tname.n = len;
-
- /* Advance zCsr to the next token. Store that token type in 'token',
- ** and its length in 'len' (to be used next iteration of this loop).
- */
- do
- {
- zCsr += len;
- len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token );
- } while ( token == TK_SPACE );
- Debug.Assert( len > 0 );
-
- /* Variable 'dist' stores the number of tokens read since the most
- ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
- ** token is read and 'dist' equals 2, the condition stated above
- ** to be met.
- **
- ** Note that ON cannot be a database, table or column name, so
- ** there is no need to worry about syntax like
- ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
- */
- dist++;
- if ( token == TK_DOT || token == TK_ON )
- {
- dist = 0;
- }
- } while ( dist != 2 || ( token != TK_WHEN && token != TK_FOR && token != TK_BEGIN ) );
-
- /* Variable tname now contains the token that is the old table-name
- ** in the CREATE TRIGGER statement.
- */
- zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ),
- zTableName, zSql.Substring( zLoc + tname.n ) );
- sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC );
- }
-}
+ /* This function is used by SQL generated to implement the
+ ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
+ ** statement. The second is a table name. The table name in the CREATE
+ ** TRIGGER statement is replaced with the third argument and the result
+ ** returned. This is analagous to renameTableFunc() above, except for CREATE
+ ** TRIGGER, not CREATE INDEX and CREATE TABLE.
+ */
+ static void renameTriggerFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] argv
+ ) {
+ string zSql = sqlite3_value_text(argv[0]);
+ string zTableName = sqlite3_value_text(argv[1]);
+
+ int token = 0;
+ Token tname = new Token();
+ int dist = 3;
+ int zCsr = 0;
+ int zLoc = 0;
+ int len = 1;
+ string zRet;
+
+ sqlite3 db = sqlite3_context_db_handle(context);
+
+ UNUSED_PARAMETER(NotUsed);
+
+ /* The principle used to locate the table name in the CREATE TRIGGER
+ ** statement is that the table name is the first token that is immediatedly
+ ** preceded by either TK_ON or TK_DOT and immediatedly followed by one
+ ** of TK_WHEN, TK_BEGIN or TK_FOR.
+ */
+ if (zSql != null) {
+ do {
+
+ if (zCsr == zSql.Length) {
+ /* Ran out of input before finding the table name. Return NULL. */
+ return;
+ }
+
+ /* Store the token that zCsr points to in tname. */
+ zLoc = zCsr;
+ tname.z = zSql.Substring(zCsr, len);//(char*)zCsr;
+ tname.n = len;
+
+ /* Advance zCsr to the next token. Store that token type in 'token',
+ ** and its length in 'len' (to be used next iteration of this loop).
+ */
+ do {
+ zCsr += len;
+ len = (zCsr == zSql.Length) ? 1 : sqlite3GetToken(zSql, zCsr, ref token);
+ } while (token == TK_SPACE);
+ Debug.Assert(len > 0);
+
+ /* Variable 'dist' stores the number of tokens read since the most
+ ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
+ ** token is read and 'dist' equals 2, the condition stated above
+ ** to be met.
+ **
+ ** Note that ON cannot be a database, table or column name, so
+ ** there is no need to worry about syntax like
+ ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
+ */
+ dist++;
+ if (token == TK_DOT || token == TK_ON) {
+ dist = 0;
+ }
+ } while (dist != 2 || (token != TK_WHEN && token != TK_FOR && token != TK_BEGIN));
+
+ /* Variable tname now contains the token that is the old table-name
+ ** in the CREATE TRIGGER statement.
+ */
+ zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", zLoc, zSql.Substring(0, zLoc),
+ zTableName, zSql.Substring(zLoc + tname.n));
+ sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
+ }
+ }
#endif // * !SQLITE_OMIT_TRIGGER */
-/*
-** Register built-in functions used to help implement ALTER TABLE
-*/
-static FuncDef[] aAlterTableFuncs;
-static void sqlite3AlterFunctions()
-{
- aAlterTableFuncs = new FuncDef[] {
+ /*
+ ** Register built-in functions used to help implement ALTER TABLE
+ */
+ static FuncDef[] aAlterTableFuncs;
+ static void sqlite3AlterFunctions() {
+ aAlterTableFuncs = new FuncDef[] {
FUNCTION("sqlite_rename_table", 2, 0, 0, renameTableFunc),
#if !SQLITE_OMIT_TRIGGER
FUNCTION("sqlite_rename_trigger", 2, 0, 0, renameTriggerFunc),
@@ -281,249 +262,227 @@ static void sqlite3AlterFunctions()
FUNCTION("sqlite_rename_parent", 3, 0, 0, renameParentFunc),
#endif
};
- int i;
+ int i;
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
FuncDef[] aFunc = GLOBAL(FuncDef, aAlterTableFuncs);
#else
- FuncDefHash pHash = sqlite3GlobalFunctions;
- FuncDef[] aFunc = aAlterTableFuncs;
+ FuncDefHash pHash = sqlite3GlobalFunctions;
+ FuncDef[] aFunc = aAlterTableFuncs;
#endif
- for ( i = 0; i < ArraySize( aAlterTableFuncs ); i++ )
- {
- sqlite3FuncDefInsert( pHash, aFunc[i] );
- }
-}
-
-/*
-** This function is used to create the text of expressions of the form:
-**
-** name= OR name= OR ...
-**
-** If argument zWhere is NULL, then a pointer string containing the text
-** "name=" is returned, where is the quoted version
-** of the string passed as argument zConstant. The returned buffer is
-** allocated using sqlite3DbMalloc(). It is the responsibility of the
-** caller to ensure that it is eventually freed.
-**
-** If argument zWhere is not NULL, then the string returned is
-** " OR name=", where is the contents of zWhere.
-** In this case zWhere is passed to sqlite3DbFree() before returning.
-**
-*/
-static string whereOrName( sqlite3 db, string zWhere, string zConstant )
-{
- string zNew;
- if ( String.IsNullOrEmpty( zWhere ) )
- {
- zNew = sqlite3MPrintf( db, "name=%Q", zConstant );
- }
- else
- {
- zNew = sqlite3MPrintf( db, "%s OR name=%Q", zWhere, zConstant );
- sqlite3DbFree( db, ref zWhere );
- }
- return zNew;
-}
+ for (i = 0; i < ArraySize(aAlterTableFuncs); i++) {
+ sqlite3FuncDefInsert(pHash, aFunc[i]);
+ }
+ }
+
+ /*
+ ** This function is used to create the text of expressions of the form:
+ **
+ ** name= OR name= OR ...
+ **
+ ** If argument zWhere is NULL, then a pointer string containing the text
+ ** "name=" is returned, where is the quoted version
+ ** of the string passed as argument zConstant. The returned buffer is
+ ** allocated using sqlite3DbMalloc(). It is the responsibility of the
+ ** caller to ensure that it is eventually freed.
+ **
+ ** If argument zWhere is not NULL, then the string returned is
+ ** " OR name=", where is the contents of zWhere.
+ ** In this case zWhere is passed to sqlite3DbFree() before returning.
+ **
+ */
+ static string whereOrName(sqlite3 db, string zWhere, string zConstant) {
+ string zNew;
+ if (String.IsNullOrEmpty(zWhere)) {
+ zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
+ } else {
+ zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
+ sqlite3DbFree(db, ref zWhere);
+ }
+ return zNew;
+ }
#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
-/*
-** Generate the text of a WHERE expression which can be used to select all
-** tables that have foreign key constraints that refer to table pTab (i.e.
-** constraints for which pTab is the parent table) from the sqlite_master
-** table.
-*/
-static string whereForeignKeys( Parse pParse, Table pTab )
-{
- FKey p;
- string zWhere = "";
- for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo )
- {
- zWhere = whereOrName( pParse.db, zWhere, p.pFrom.zName );
- }
- return zWhere;
-}
+ /*
+ ** Generate the text of a WHERE expression which can be used to select all
+ ** tables that have foreign key constraints that refer to table pTab (i.e.
+ ** constraints for which pTab is the parent table) from the sqlite_master
+ ** table.
+ */
+ static string whereForeignKeys(Parse pParse, Table pTab) {
+ FKey p;
+ string zWhere = "";
+ for (p = sqlite3FkReferences(pTab); p != null; p = p.pNextTo) {
+ zWhere = whereOrName(pParse.db, zWhere, p.pFrom.zName);
+ }
+ return zWhere;
+ }
#endif
-/*
-** Generate the text of a WHERE expression which can be used to select all
-** temporary triggers on table pTab from the sqlite_temp_master table. If
-** table pTab has no temporary triggers, or is itself stored in the
-** temporary database, NULL is returned.
-*/
-static string whereTempTriggers( Parse pParse, Table pTab )
-{
- Trigger pTrig;
- string zWhere = "";
- Schema pTempSchema = pParse.db.aDb[1].pSchema; /* Temp db schema */
-
- /* If the table is not located in the temp.db (in which case NULL is
- ** returned, loop through the tables list of triggers. For each trigger
- ** that is not part of the temp.db schema, add a clause to the WHERE
- ** expression being built up in zWhere.
- */
- if ( pTab.pSchema != pTempSchema )
- {
- sqlite3 db = pParse.db;
- for ( pTrig = sqlite3TriggerList( pParse, pTab ); pTrig != null; pTrig = pTrig.pNext )
- {
- if ( pTrig.pSchema == pTempSchema )
- {
- zWhere = whereOrName( db, zWhere, pTrig.zName );
- }
- }
- }
- if ( !String.IsNullOrEmpty( zWhere ) )
- {
- zWhere = sqlite3MPrintf( pParse.db, "type='trigger' AND (%s)", zWhere );
- //sqlite3DbFree( pParse.db, ref zWhere );
- //zWhere = zNew;
- }
- return zWhere;
-}
-
-/*
-** Generate code to drop and reload the internal representation of table
-** pTab from the database, including triggers and temporary triggers.
-** Argument zName is the name of the table in the database schema at
-** the time the generated code is executed. This can be different from
-** pTab.zName if this function is being called to code part of an
-** "ALTER TABLE RENAME TO" statement.
-*/
-static void reloadTableSchema( Parse pParse, Table pTab, string zName )
-{
- Vdbe v;
- string zWhere;
- int iDb; /* Index of database containing pTab */
+ /*
+ ** Generate the text of a WHERE expression which can be used to select all
+ ** temporary triggers on table pTab from the sqlite_temp_master table. If
+ ** table pTab has no temporary triggers, or is itself stored in the
+ ** temporary database, NULL is returned.
+ */
+ static string whereTempTriggers(Parse pParse, Table pTab) {
+ Trigger pTrig;
+ string zWhere = "";
+ Schema pTempSchema = pParse.db.aDb[1].pSchema; /* Temp db schema */
+
+ /* If the table is not located in the temp.db (in which case NULL is
+ ** returned, loop through the tables list of triggers. For each trigger
+ ** that is not part of the temp.db schema, add a clause to the WHERE
+ ** expression being built up in zWhere.
+ */
+ if (pTab.pSchema != pTempSchema) {
+ sqlite3 db = pParse.db;
+ for (pTrig = sqlite3TriggerList(pParse, pTab); pTrig != null; pTrig = pTrig.pNext) {
+ if (pTrig.pSchema == pTempSchema) {
+ zWhere = whereOrName(db, zWhere, pTrig.zName);
+ }
+ }
+ }
+ if (!String.IsNullOrEmpty(zWhere)) {
+ zWhere = sqlite3MPrintf(pParse.db, "type='trigger' AND (%s)", zWhere);
+ //sqlite3DbFree( pParse.db, ref zWhere );
+ //zWhere = zNew;
+ }
+ return zWhere;
+ }
+
+ /*
+ ** Generate code to drop and reload the internal representation of table
+ ** pTab from the database, including triggers and temporary triggers.
+ ** Argument zName is the name of the table in the database schema at
+ ** the time the generated code is executed. This can be different from
+ ** pTab.zName if this function is being called to code part of an
+ ** "ALTER TABLE RENAME TO" statement.
+ */
+ static void reloadTableSchema(Parse pParse, Table pTab, string zName) {
+ Vdbe v;
+ string zWhere;
+ int iDb; /* Index of database containing pTab */
#if !SQLITE_OMIT_TRIGGER
- Trigger pTrig;
+ Trigger pTrig;
#endif
- v = sqlite3GetVdbe( pParse );
- if ( NEVER( v == null ) )
- return;
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
- iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
- Debug.Assert( iDb >= 0 );
+ v = sqlite3GetVdbe(pParse);
+ if (NEVER(v == null))
+ return;
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
+ iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
+ Debug.Assert(iDb >= 0);
#if !SQLITE_OMIT_TRIGGER
- /* Drop any table triggers from the internal schema. */
- for ( pTrig = sqlite3TriggerList( pParse, pTab ); pTrig != null; pTrig = pTrig.pNext )
- {
- int iTrigDb = sqlite3SchemaToIndex( pParse.db, pTrig.pSchema );
- Debug.Assert( iTrigDb == iDb || iTrigDb == 1 );
- sqlite3VdbeAddOp4( v, OP_DropTrigger, iTrigDb, 0, 0, pTrig.zName, 0 );
- }
+ /* Drop any table triggers from the internal schema. */
+ for (pTrig = sqlite3TriggerList(pParse, pTab); pTrig != null; pTrig = pTrig.pNext) {
+ int iTrigDb = sqlite3SchemaToIndex(pParse.db, pTrig.pSchema);
+ Debug.Assert(iTrigDb == iDb || iTrigDb == 1);
+ sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig.zName, 0);
+ }
#endif
- /* Drop the table and index from the internal schema. */
- sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 );
+ /* Drop the table and index from the internal schema. */
+ sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab.zName, 0);
- /* Reload the table, index and permanent trigger schemas. */
- zWhere = sqlite3MPrintf( pParse.db, "tbl_name=%Q", zName );
- if ( zWhere == null )
- return;
- sqlite3VdbeAddParseSchemaOp( v, iDb, zWhere );
+ /* Reload the table, index and permanent trigger schemas. */
+ zWhere = sqlite3MPrintf(pParse.db, "tbl_name=%Q", zName);
+ if (zWhere == null)
+ return;
+ sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
#if !SQLITE_OMIT_TRIGGER
- /* Now, if the table is not stored in the temp database, reload any temp
-** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
-*/
- if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" )
- {
- sqlite3VdbeAddParseSchemaOp( v, 1, zWhere );
- }
+ /* Now, if the table is not stored in the temp database, reload any temp
+ ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
+ */
+ if ((zWhere = whereTempTriggers(pParse, pTab)) != "") {
+ sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
+ }
#endif
-}
-
-/*
-** Parameter zName is the name of a table that is about to be altered
-** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
-** If the table is a system table, this function leaves an error message
-** in pParse->zErr (system tables may not be altered) and returns non-zero.
-**
-** Or, if zName is not a system table, zero is returned.
-*/
-static int isSystemTable( Parse pParse, string zName )
-{
- if (zName.StartsWith("sqlite_", System.StringComparison.OrdinalIgnoreCase))
- {
- sqlite3ErrorMsg( pParse, "table %s may not be altered", zName );
- return 1;
- }
- return 0;
-}
-
-/*
-** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
-** command.
-*/
-static void sqlite3AlterRenameTable(
-Parse pParse, /* Parser context. */
-SrcList pSrc, /* The table to rename. */
-Token pName /* The new table name. */
-)
-{
- int iDb; /* Database that contains the table */
- string zDb; /* Name of database iDb */
- Table pTab; /* Table being renamed */
- string zName = null; /* NULL-terminated version of pName */
- sqlite3 db = pParse.db; /* Database connection */
- int nTabName; /* Number of UTF-8 characters in zTabName */
- string zTabName; /* Original name of the table */
- Vdbe v;
+ }
+
+ /*
+ ** Parameter zName is the name of a table that is about to be altered
+ ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
+ ** If the table is a system table, this function leaves an error message
+ ** in pParse->zErr (system tables may not be altered) and returns non-zero.
+ **
+ ** Or, if zName is not a system table, zero is returned.
+ */
+ static int isSystemTable(Parse pParse, string zName) {
+ if (zName.StartsWith("sqlite_", System.StringComparison.OrdinalIgnoreCase)) {
+ sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
+ return 1;
+ }
+ return 0;
+ }
+
+ /*
+ ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
+ ** command.
+ */
+ static void sqlite3AlterRenameTable(
+ Parse pParse, /* Parser context. */
+ SrcList pSrc, /* The table to rename. */
+ Token pName /* The new table name. */
+ ) {
+ int iDb; /* Database that contains the table */
+ string zDb; /* Name of database iDb */
+ Table pTab; /* Table being renamed */
+ string zName = null; /* NULL-terminated version of pName */
+ sqlite3 db = pParse.db; /* Database connection */
+ int nTabName; /* Number of UTF-8 characters in zTabName */
+ string zTabName; /* Original name of the table */
+ Vdbe v;
#if !SQLITE_OMIT_TRIGGER
- string zWhere = ""; /* Where clause to locate temp triggers */
+ string zWhere = ""; /* Where clause to locate temp triggers */
#endif
- VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */
- int savedDbFlags; /* Saved value of db->flags */
-
- savedDbFlags = db.flags;
-
- //if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table;
- Debug.Assert( pSrc.nSrc == 1 );
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
- pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase );
- if ( pTab == null )
- goto exit_rename_table;
- iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
- zDb = db.aDb[iDb].zName;
- db.flags |= SQLITE_PreferBuiltin;
-
- /* Get a NULL terminated version of the new table name. */
- zName = sqlite3NameFromToken( db, pName );
- if ( zName == null )
- goto exit_rename_table;
-
- /* Check that a table or index named 'zName' does not already exist
- ** in database iDb. If so, this is an error.
- */
- if ( sqlite3FindTable( db, zName, zDb ) != null || sqlite3FindIndex( db, zName, zDb ) != null )
- {
- sqlite3ErrorMsg( pParse,
- "there is already another table or index with this name: %s", zName );
- goto exit_rename_table;
- }
-
- /* Make sure it is not a system table being altered, or a reserved name
- ** that the table is being renamed to.
- */
- if ( SQLITE_OK!=isSystemTable(pParse, pTab.zName) )
- {
- goto exit_rename_table;
- }
- if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
- {
- goto exit_rename_table;
- }
+ VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */
+ int savedDbFlags; /* Saved value of db->flags */
+
+ savedDbFlags = db.flags;
+
+ //if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table;
+ Debug.Assert(pSrc.nSrc == 1);
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
+ pTab = sqlite3LocateTable(pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase);
+ if (pTab == null)
+ goto exit_rename_table;
+ iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
+ zDb = db.aDb[iDb].zName;
+ db.flags |= SQLITE_PreferBuiltin;
+
+ /* Get a NULL terminated version of the new table name. */
+ zName = sqlite3NameFromToken(db, pName);
+ if (zName == null)
+ goto exit_rename_table;
+
+ /* Check that a table or index named 'zName' does not already exist
+ ** in database iDb. If so, this is an error.
+ */
+ if (sqlite3FindTable(db, zName, zDb) != null || sqlite3FindIndex(db, zName, zDb) != null) {
+ sqlite3ErrorMsg(pParse,
+ "there is already another table or index with this name: %s", zName);
+ goto exit_rename_table;
+ }
+
+ /* Make sure it is not a system table being altered, or a reserved name
+ ** that the table is being renamed to.
+ */
+ if (SQLITE_OK != isSystemTable(pParse, pTab.zName)) {
+ goto exit_rename_table;
+ }
+ if (SQLITE_OK != sqlite3CheckObjectName(pParse, zName)) {
+ goto exit_rename_table;
+ }
#if !SQLITE_OMIT_VIEW
- if ( pTab.pSelect != null )
- {
- sqlite3ErrorMsg( pParse, "view %s may not be altered", pTab.zName );
- goto exit_rename_table;
- }
+ if (pTab.pSelect != null) {
+ sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab.zName);
+ goto exit_rename_table;
+ }
#endif
#if !SQLITE_OMIT_AUTHORIZATION
@@ -533,207 +492,192 @@ static void sqlite3AlterRenameTable(
}
#endif
- if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
- {
- goto exit_rename_table;
- }
+ if (sqlite3ViewGetColumnNames(pParse, pTab) != 0) {
+ goto exit_rename_table;
+ }
#if !SQLITE_OMIT_VIRTUALTABLE
- if ( IsVirtual( pTab ) )
- {
- pVTab = sqlite3GetVTable( db, pTab );
- if ( pVTab.pVtab.pModule.xRename == null )
- {
- pVTab = null;
- }
- }
+ if (IsVirtual(pTab)) {
+ pVTab = sqlite3GetVTable(db, pTab);
+ if (pVTab.pVtab.pModule.xRename == null) {
+ pVTab = null;
+ }
+ }
#endif
- /* Begin a transaction and code the VerifyCookie for database iDb.
-** Then modify the schema cookie (since the ALTER TABLE modifies the
-** schema). Open a statement transaction if the table is a virtual
-** table.
-*/
- v = sqlite3GetVdbe( pParse );
- if ( v == null )
- {
- goto exit_rename_table;
- }
- sqlite3BeginWriteOperation( pParse, pVTab != null ? 1 : 0, iDb );
- sqlite3ChangeCookie( pParse, iDb );
-
- /* If this is a virtual table, invoke the xRename() function if
- ** one is defined. The xRename() callback will modify the names
- ** of any resources used by the v-table implementation (including other
- ** SQLite tables) that are identified by the name of the virtual table.
- */
-#if !SQLITE_OMIT_VIRTUALTABLE
-if ( pVTab !=null)
-{
-int i = ++pParse.nMem;
-sqlite3VdbeAddOp4( v, OP_String8, 0, i, 0, zName, 0 );
-sqlite3VdbeAddOp4( v, OP_VRename, i, 0, 0, pVTab, P4_VTAB );
-sqlite3MayAbort(pParse);
-}
+ /* Begin a transaction and code the VerifyCookie for database iDb.
+ ** Then modify the schema cookie (since the ALTER TABLE modifies the
+ ** schema). Open a statement transaction if the table is a virtual
+ ** table.
+ */
+ v = sqlite3GetVdbe(pParse);
+ if (v == null) {
+ goto exit_rename_table;
+ }
+ sqlite3BeginWriteOperation(pParse, pVTab != null ? 1 : 0, iDb);
+ sqlite3ChangeCookie(pParse, iDb);
+
+ /* If this is a virtual table, invoke the xRename() function if
+ ** one is defined. The xRename() callback will modify the names
+ ** of any resources used by the v-table implementation (including other
+ ** SQLite tables) that are identified by the name of the virtual table.
+ */
+#if !SQLITE_OMIT_VIRTUALTABLE
+ if (pVTab != null) {
+ int i = ++pParse.nMem;
+ sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
+ sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0, pVTab, P4_VTAB);
+ sqlite3MayAbort(pParse);
+ }
#endif
- /* figure out how many UTF-8 characters are in zName */
- zTabName = pTab.zName;
- nTabName = sqlite3Utf8CharLen( zTabName, -1 );
+ /* figure out how many UTF-8 characters are in zName */
+ zTabName = pTab.zName;
+ nTabName = sqlite3Utf8CharLen(zTabName, -1);
#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
- if ( ( db.flags & SQLITE_ForeignKeys ) != 0 )
- {
- /* If foreign-key support is enabled, rewrite the CREATE TABLE
- ** statements corresponding to all child tables of foreign key constraints
- ** for which the renamed table is the parent table. */
- if ( ( zWhere = whereForeignKeys( pParse, pTab ) ) != null )
- {
- sqlite3NestedParse( pParse,
- "UPDATE \"%w\".%s SET " +
- "sql = sqlite_rename_parent(sql, %Q, %Q) " +
- "WHERE %s;", zDb, SCHEMA_TABLE( iDb ), zTabName, zName, zWhere );
- sqlite3DbFree( db, ref zWhere );
- }
- }
+ if ((db.flags & SQLITE_ForeignKeys) != 0) {
+ /* If foreign-key support is enabled, rewrite the CREATE TABLE
+ ** statements corresponding to all child tables of foreign key constraints
+ ** for which the renamed table is the parent table. */
+ if ((zWhere = whereForeignKeys(pParse, pTab)) != null) {
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\".%s SET " +
+ "sql = sqlite_rename_parent(sql, %Q, %Q) " +
+ "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
+ sqlite3DbFree(db, ref zWhere);
+ }
+ }
#endif
- /* Modify the sqlite_master table to use the new table name. */
- sqlite3NestedParse( pParse,
- "UPDATE %Q.%s SET " +
+ /* Modify the sqlite_master table to use the new table name. */
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q.%s SET " +
#if SQLITE_OMIT_TRIGGER
"sql = sqlite_rename_table(sql, %Q), " +
#else
- "sql = CASE " +
- "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" +
- "ELSE sqlite_rename_table(sql, %Q) END, " +
+ "sql = CASE " +
+ "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" +
+ "ELSE sqlite_rename_table(sql, %Q) END, " +
#endif
- "tbl_name = %Q, " +
- "name = CASE " +
- "WHEN type='table' THEN %Q " +
- "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " +
- "'sqlite_autoindex_' || %Q || substr(name,%d+18) " +
- "ELSE name END " +
- "WHERE tbl_name=%Q AND " +
- "(type='table' OR type='index' OR type='trigger');",
- zDb, SCHEMA_TABLE( iDb ), zName, zName, zName,
+ "tbl_name = %Q, " +
+ "name = CASE " +
+ "WHEN type='table' THEN %Q " +
+ "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " +
+ "'sqlite_autoindex_' || %Q || substr(name,%d+18) " +
+ "ELSE name END " +
+ "WHERE tbl_name=%Q AND " +
+ "(type='table' OR type='index' OR type='trigger');",
+ zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
#if !SQLITE_OMIT_TRIGGER
- zName,
+ zName,
#endif
- zName, nTabName, zTabName
- );
+ zName, nTabName, zTabName
+ );
#if !SQLITE_OMIT_AUTOINCREMENT
- /* If the sqlite_sequence table exists in this database, then update
-** it with the new table name.
-*/
- if ( sqlite3FindTable( db, "sqlite_sequence", zDb ) != null )
- {
- sqlite3NestedParse( pParse,
- "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
- zDb, zName, pTab.zName
- );
- }
+ /* If the sqlite_sequence table exists in this database, then update
+ ** it with the new table name.
+ */
+ if (sqlite3FindTable(db, "sqlite_sequence", zDb) != null) {
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
+ zDb, zName, pTab.zName
+ );
+ }
#endif
#if !SQLITE_OMIT_TRIGGER
- /* If there are TEMP triggers on this table, modify the sqlite_temp_master
-** table. Don't do this if the table being ALTERed is itself located in
-** the temp database.
-*/
- if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" )
- {
- sqlite3NestedParse( pParse,
- "UPDATE sqlite_temp_master SET " +
- "sql = sqlite_rename_trigger(sql, %Q), " +
- "tbl_name = %Q " +
- "WHERE %s;", zName, zName, zWhere );
- sqlite3DbFree( db, ref zWhere );
- }
+ /* If there are TEMP triggers on this table, modify the sqlite_temp_master
+ ** table. Don't do this if the table being ALTERed is itself located in
+ ** the temp database.
+ */
+ if ((zWhere = whereTempTriggers(pParse, pTab)) != "") {
+ sqlite3NestedParse(pParse,
+ "UPDATE sqlite_temp_master SET " +
+ "sql = sqlite_rename_trigger(sql, %Q), " +
+ "tbl_name = %Q " +
+ "WHERE %s;", zName, zName, zWhere);
+ sqlite3DbFree(db, ref zWhere);
+ }
#endif
#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
- if ( ( db.flags & SQLITE_ForeignKeys ) != 0 )
- {
- FKey p;
- for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo )
- {
- Table pFrom = p.pFrom;
- if ( pFrom != pTab )
- {
- reloadTableSchema( pParse, p.pFrom, pFrom.zName );
- }
- }
- }
+ if ((db.flags & SQLITE_ForeignKeys) != 0) {
+ FKey p;
+ for (p = sqlite3FkReferences(pTab); p != null; p = p.pNextTo) {
+ Table pFrom = p.pFrom;
+ if (pFrom != pTab) {
+ reloadTableSchema(pParse, p.pFrom, pFrom.zName);
+ }
+ }
+ }
#endif
- /* Drop and reload the internal table schema. */
- reloadTableSchema( pParse, pTab, zName );
-
-exit_rename_table:
- sqlite3SrcListDelete( db, ref pSrc );
- sqlite3DbFree( db, ref zName );
- db.flags = savedDbFlags;
-}
-
-/*
-** Generate code to make sure the file format number is at least minFormat.
-** The generated code will increase the file format number if necessary.
-*/
-static void sqlite3MinimumFileFormat( Parse pParse, int iDb, int minFormat )
-{
- Vdbe v;
- v = sqlite3GetVdbe( pParse );
- /* The VDBE should have been allocated before this routine is called.
- ** If that allocation failed, we would have quit before reaching this
- ** point */
- if ( ALWAYS( v ) )
- {
- int r1 = sqlite3GetTempReg( pParse );
- int r2 = sqlite3GetTempReg( pParse );
- int j1;
- sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT );
- sqlite3VdbeUsesBtree( v, iDb );
- sqlite3VdbeAddOp2( v, OP_Integer, minFormat, r2 );
- j1 = sqlite3VdbeAddOp3( v, OP_Ge, r2, 0, r1 );
- sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2 );
- sqlite3VdbeJumpHere( v, j1 );
- sqlite3ReleaseTempReg( pParse, r1 );
- sqlite3ReleaseTempReg( pParse, r2 );
- }
-}
-
-/*
-** This function is called after an "ALTER TABLE ... ADD" statement
-** has been parsed. Argument pColDef contains the text of the new
-** column definition.
-**
-** The Table structure pParse.pNewTable was extended to include
-** the new column during parsing.
-*/
-static void sqlite3AlterFinishAddColumn( Parse pParse, Token pColDef )
-{
- Table pNew; /* Copy of pParse.pNewTable */
- Table pTab; /* Table being altered */
- int iDb; /* Database number */
- string zDb; /* Database name */
- string zTab; /* Table name */
- string zCol; /* Null-terminated column definition */
- Column pCol; /* The new column */
- Expr pDflt; /* Default value for the new column */
- sqlite3 db; /* The database connection; */
-
- db = pParse.db;
- if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
- return;
- pNew = pParse.pNewTable;
- Debug.Assert( pNew != null );
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
- iDb = sqlite3SchemaToIndex( db, pNew.pSchema );
- zDb = db.aDb[iDb].zName;
- zTab = pNew.zName.Substring( 16 );// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
- pCol = pNew.aCol[pNew.nCol - 1];
- pDflt = pCol.pDflt;
- pTab = sqlite3FindTable( db, zTab, zDb );
- Debug.Assert( pTab != null );
+ /* Drop and reload the internal table schema. */
+ reloadTableSchema(pParse, pTab, zName);
+
+ exit_rename_table:
+ sqlite3SrcListDelete(db, ref pSrc);
+ sqlite3DbFree(db, ref zName);
+ db.flags = savedDbFlags;
+ }
+
+ /*
+ ** Generate code to make sure the file format number is at least minFormat.
+ ** The generated code will increase the file format number if necessary.
+ */
+ static void sqlite3MinimumFileFormat(Parse pParse, int iDb, int minFormat) {
+ Vdbe v;
+ v = sqlite3GetVdbe(pParse);
+ /* The VDBE should have been allocated before this routine is called.
+ ** If that allocation failed, we would have quit before reaching this
+ ** point */
+ if (ALWAYS(v)) {
+ int r1 = sqlite3GetTempReg(pParse);
+ int r2 = sqlite3GetTempReg(pParse);
+ int j1;
+ sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
+ sqlite3VdbeUsesBtree(v, iDb);
+ sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
+ j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
+ sqlite3VdbeJumpHere(v, j1);
+ sqlite3ReleaseTempReg(pParse, r1);
+ sqlite3ReleaseTempReg(pParse, r2);
+ }
+ }
+
+ /*
+ ** This function is called after an "ALTER TABLE ... ADD" statement
+ ** has been parsed. Argument pColDef contains the text of the new
+ ** column definition.
+ **
+ ** The Table structure pParse.pNewTable was extended to include
+ ** the new column during parsing.
+ */
+ static void sqlite3AlterFinishAddColumn(Parse pParse, Token pColDef) {
+ Table pNew; /* Copy of pParse.pNewTable */
+ Table pTab; /* Table being altered */
+ int iDb; /* Database number */
+ string zDb; /* Database name */
+ string zTab; /* Table name */
+ string zCol; /* Null-terminated column definition */
+ Column pCol; /* The new column */
+ Expr pDflt; /* Default value for the new column */
+ sqlite3 db; /* The database connection; */
+
+ db = pParse.db;
+ if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
+ return;
+ pNew = pParse.pNewTable;
+ Debug.Assert(pNew != null);
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
+ iDb = sqlite3SchemaToIndex(db, pNew.pSchema);
+ zDb = db.aDb[iDb].zName;
+ zTab = pNew.zName.Substring(16);// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
+ pCol = pNew.aCol[pNew.nCol - 1];
+ pDflt = pCol.pDflt;
+ pTab = sqlite3FindTable(db, zTab, zDb);
+ Debug.Assert(pTab != null);
#if !SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
@@ -742,194 +686,179 @@ static void sqlite3AlterFinishAddColumn( Parse pParse, Token pColDef )
}
#endif
- /* If the default value for the new column was specified with a
-** literal NULL, then set pDflt to 0. This simplifies checking
-** for an SQL NULL default below.
-*/
- if ( pDflt != null && pDflt.op == TK_NULL )
- {
- pDflt = null;
- }
-
- /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
- ** If there is a NOT NULL constraint, then the default value for the
- ** column must not be NULL.
- */
- if ( pCol.isPrimKey != 0 )
- {
- sqlite3ErrorMsg( pParse, "Cannot add a PRIMARY KEY column" );
- return;
- }
- if ( pNew.pIndex != null )
- {
- sqlite3ErrorMsg( pParse, "Cannot add a UNIQUE column" );
- return;
- }
- if ( ( db.flags & SQLITE_ForeignKeys ) != 0 && pNew.pFKey != null && pDflt != null )
- {
- sqlite3ErrorMsg( pParse,
- "Cannot add a REFERENCES column with non-NULL default value" );
- return;
- }
- if ( pCol.notNull != 0 && pDflt == null )
- {
- sqlite3ErrorMsg( pParse,
- "Cannot add a NOT NULL column with default value NULL" );
- return;
- }
-
- /* Ensure the default expression is something that sqlite3ValueFromExpr()
- ** can handle (i.e. not CURRENT_TIME etc.)
- */
- if ( pDflt != null )
- {
- sqlite3_value pVal = null;
- if ( sqlite3ValueFromExpr( db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal ) != 0 )
- {
- // db.mallocFailed = 1;
- return;
- }
- if ( pVal == null )
- {
- sqlite3ErrorMsg( pParse, "Cannot add a column with non-constant default" );
- return;
- }
- sqlite3ValueFree( ref pVal );
- }
-
- /* Modify the CREATE TABLE statement. */
- zCol = pColDef.z.Substring( 0, pColDef.n ).Replace( ";", " " ).Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n);
- if ( zCol != null )
- {
- // char zEnd = zCol[pColDef.n-1];
- int savedDbFlags = db.flags;
- // while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
- // zEnd-- = '\0';
- // }
- db.flags |= SQLITE_PreferBuiltin;
- sqlite3NestedParse( pParse,
- "UPDATE \"%w\".%s SET " +
- "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " +
- "WHERE type = 'table' AND name = %Q",
- zDb, SCHEMA_TABLE( iDb ), pNew.addColOffset, zCol, pNew.addColOffset + 1,
- zTab
- );
- sqlite3DbFree( db, ref zCol );
- db.flags = savedDbFlags;
- }
-
- /* If the default value of the new column is NULL, then set the file
- ** format to 2. If the default value of the new column is not NULL,
- ** the file format becomes 3.
- */
- sqlite3MinimumFileFormat( pParse, iDb, pDflt != null ? 3 : 2 );
-
- /* Reload the schema of the modified table. */
- reloadTableSchema( pParse, pTab, pTab.zName );
-}
-
-/*
-** This function is called by the parser after the table-name in
-** an "ALTER TABLE ADD" statement is parsed. Argument
-** pSrc is the full-name of the table being altered.
-**
-** This routine makes a (partial) copy of the Table structure
-** for the table being altered and sets Parse.pNewTable to point
-** to it. Routines called by the parser as the column definition
-** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
-** the copy. The copy of the Table structure is deleted by tokenize.c
-** after parsing is finished.
-**
-** Routine sqlite3AlterFinishAddColumn() will be called to complete
-** coding the "ALTER TABLE ... ADD" statement.
-*/
-static void sqlite3AlterBeginAddColumn( Parse pParse, SrcList pSrc )
-{
- Table pNew;
- Table pTab;
- Vdbe v;
- int iDb;
- int i;
- int nAlloc;
- sqlite3 db = pParse.db;
-
- /* Look up the table being altered. */
- Debug.Assert( pParse.pNewTable == null );
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
- // if ( db.mallocFailed != 0 ) goto exit_begin_add_column;
- pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase );
- if ( pTab == null )
- goto exit_begin_add_column;
-
- if ( IsVirtual( pTab ) )
- {
- sqlite3ErrorMsg( pParse, "virtual tables may not be altered" );
- goto exit_begin_add_column;
- }
-
- /* Make sure this is not an attempt to ALTER a view. */
- if ( pTab.pSelect != null )
- {
- sqlite3ErrorMsg( pParse, "Cannot add a column to a view" );
- goto exit_begin_add_column;
- }
- if ( SQLITE_OK != isSystemTable( pParse, pTab.zName ) )
- {
- goto exit_begin_add_column;
- }
-
- Debug.Assert( pTab.addColOffset > 0 );
- iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
-
- /* Put a copy of the Table struct in Parse.pNewTable for the
- ** sqlite3AddColumn() function and friends to modify. But modify
- ** the name by adding an "sqlite_altertab_" prefix. By adding this
- ** prefix, we insure that the name will not collide with an existing
- ** table because user table are not allowed to have the "sqlite_"
- ** prefix on their name.
- */
- pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table))
- if ( pNew == null )
- goto exit_begin_add_column;
- pParse.pNewTable = pNew;
- pNew.nRef = 1;
- pNew.nCol = pTab.nCol;
- Debug.Assert( pNew.nCol > 0 );
- nAlloc = ( ( ( pNew.nCol - 1 ) / 8 ) * 8 ) + 8;
- Debug.Assert( nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8 );
- pNew.aCol = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc );
- pNew.zName = sqlite3MPrintf( db, "sqlite_altertab_%s", pTab.zName );
- if ( pNew.aCol == null || pNew.zName == null )
- {
- // db.mallocFailed = 1;
- goto exit_begin_add_column;
- }
- // memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol );
- for ( i = 0; i < pNew.nCol; i++ )
- {
- Column pCol = pTab.aCol[i].Copy();
- // sqlite3DbStrDup( db, pCol.zName );
- pCol.zColl = null;
- pCol.zType = null;
- pCol.pDflt = null;
- pCol.zDflt = null;
- pNew.aCol[i] = pCol;
- }
- pNew.pSchema = db.aDb[iDb].pSchema;
- pNew.addColOffset = pTab.addColOffset;
- pNew.nRef = 1;
-
- /* Begin a transaction and increment the schema cookie. */
- sqlite3BeginWriteOperation( pParse, 0, iDb );
- v = sqlite3GetVdbe( pParse );
- if ( v == null )
- goto exit_begin_add_column;
- sqlite3ChangeCookie( pParse, iDb );
-
-exit_begin_add_column:
- sqlite3SrcListDelete( db, ref pSrc );
- return;
-}
+ /* If the default value for the new column was specified with a
+ ** literal NULL, then set pDflt to 0. This simplifies checking
+ ** for an SQL NULL default below.
+ */
+ if (pDflt != null && pDflt.op == TK_NULL) {
+ pDflt = null;
+ }
+
+ /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
+ ** If there is a NOT NULL constraint, then the default value for the
+ ** column must not be NULL.
+ */
+ if (pCol.isPrimKey != 0) {
+ sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
+ return;
+ }
+ if (pNew.pIndex != null) {
+ sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
+ return;
+ }
+ if ((db.flags & SQLITE_ForeignKeys) != 0 && pNew.pFKey != null && pDflt != null) {
+ sqlite3ErrorMsg(pParse,
+ "Cannot add a REFERENCES column with non-NULL default value");
+ return;
+ }
+ if (pCol.notNull != 0 && pDflt == null) {
+ sqlite3ErrorMsg(pParse,
+ "Cannot add a NOT NULL column with default value NULL");
+ return;
+ }
+
+ /* Ensure the default expression is something that sqlite3ValueFromExpr()
+ ** can handle (i.e. not CURRENT_TIME etc.)
+ */
+ if (pDflt != null) {
+ sqlite3_value pVal = null;
+ if (sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal) != 0) {
+ // db.mallocFailed = 1;
+ return;
+ }
+ if (pVal == null) {
+ sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
+ return;
+ }
+ sqlite3ValueFree(ref pVal);
+ }
+
+ /* Modify the CREATE TABLE statement. */
+ zCol = pColDef.z.Substring(0, pColDef.n).Replace(";", " ").Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n);
+ if (zCol != null) {
+ // char zEnd = zCol[pColDef.n-1];
+ int savedDbFlags = db.flags;
+ // while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
+ // zEnd-- = '\0';
+ // }
+ db.flags |= SQLITE_PreferBuiltin;
+ sqlite3NestedParse(pParse,
+ "UPDATE \"%w\".%s SET " +
+ "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " +
+ "WHERE type = 'table' AND name = %Q",
+ zDb, SCHEMA_TABLE(iDb), pNew.addColOffset, zCol, pNew.addColOffset + 1,
+ zTab
+ );
+ sqlite3DbFree(db, ref zCol);
+ db.flags = savedDbFlags;
+ }
+
+ /* If the default value of the new column is NULL, then set the file
+ ** format to 2. If the default value of the new column is not NULL,
+ ** the file format becomes 3.
+ */
+ sqlite3MinimumFileFormat(pParse, iDb, pDflt != null ? 3 : 2);
+
+ /* Reload the schema of the modified table. */
+ reloadTableSchema(pParse, pTab, pTab.zName);
+ }
+
+ /*
+ ** This function is called by the parser after the table-name in
+ ** an "ALTER TABLE ADD" statement is parsed. Argument
+ ** pSrc is the full-name of the table being altered.
+ **
+ ** This routine makes a (partial) copy of the Table structure
+ ** for the table being altered and sets Parse.pNewTable to point
+ ** to it. Routines called by the parser as the column definition
+ ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
+ ** the copy. The copy of the Table structure is deleted by tokenize.c
+ ** after parsing is finished.
+ **
+ ** Routine sqlite3AlterFinishAddColumn() will be called to complete
+ ** coding the "ALTER TABLE ... ADD" statement.
+ */
+ static void sqlite3AlterBeginAddColumn(Parse pParse, SrcList pSrc) {
+ Table pNew;
+ Table pTab;
+ Vdbe v;
+ int iDb;
+ int i;
+ int nAlloc;
+ sqlite3 db = pParse.db;
+
+ /* Look up the table being altered. */
+ Debug.Assert(pParse.pNewTable == null);
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
+ // if ( db.mallocFailed != 0 ) goto exit_begin_add_column;
+ pTab = sqlite3LocateTable(pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase);
+ if (pTab == null)
+ goto exit_begin_add_column;
+
+ if (IsVirtual(pTab)) {
+ sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
+ goto exit_begin_add_column;
+ }
+
+ /* Make sure this is not an attempt to ALTER a view. */
+ if (pTab.pSelect != null) {
+ sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
+ goto exit_begin_add_column;
+ }
+ if (SQLITE_OK != isSystemTable(pParse, pTab.zName)) {
+ goto exit_begin_add_column;
+ }
+
+ Debug.Assert(pTab.addColOffset > 0);
+ iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
+
+ /* Put a copy of the Table struct in Parse.pNewTable for the
+ ** sqlite3AddColumn() function and friends to modify. But modify
+ ** the name by adding an "sqlite_altertab_" prefix. By adding this
+ ** prefix, we insure that the name will not collide with an existing
+ ** table because user table are not allowed to have the "sqlite_"
+ ** prefix on their name.
+ */
+ pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table))
+ if (pNew == null)
+ goto exit_begin_add_column;
+ pParse.pNewTable = pNew;
+ pNew.nRef = 1;
+ pNew.nCol = pTab.nCol;
+ Debug.Assert(pNew.nCol > 0);
+ nAlloc = (((pNew.nCol - 1) / 8) * 8) + 8;
+ Debug.Assert(nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8);
+ pNew.aCol = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc );
+ pNew.zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab.zName);
+ if (pNew.aCol == null || pNew.zName == null) {
+ // db.mallocFailed = 1;
+ goto exit_begin_add_column;
+ }
+ // memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol );
+ for (i = 0; i < pNew.nCol; i++) {
+ Column pCol = pTab.aCol[i].Copy();
+ // sqlite3DbStrDup( db, pCol.zName );
+ pCol.zColl = null;
+ pCol.zType = null;
+ pCol.pDflt = null;
+ pCol.zDflt = null;
+ pNew.aCol[i] = pCol;
+ }
+ pNew.pSchema = db.aDb[iDb].pSchema;
+ pNew.addColOffset = pTab.addColOffset;
+ pNew.nRef = 1;
+
+ /* Begin a transaction and increment the schema cookie. */
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ v = sqlite3GetVdbe(pParse);
+ if (v == null)
+ goto exit_begin_add_column;
+ sqlite3ChangeCookie(pParse, iDb);
+
+ exit_begin_add_column:
+ sqlite3SrcListDelete(db, ref pSrc);
+ return;
+ }
#endif // * SQLITE_ALTER_TABLE */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/analyze_c.cs b/Src/IronPython.SQLite/c#sqlite/analyze_c.cs
index 23d5cd4ce..899ab6392 100644
--- a/Src/IronPython.SQLite/c#sqlite/analyze_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/analyze_c.cs
@@ -1,168 +1,152 @@
using System;
using System.Diagnostics;
-using System.Text;
using u8 = System.Byte;
-namespace Community.CsharpSqlite
-{
- using sqlite3_int64 = System.Int64;
- using sqlite3_stmt = Sqlite3.Vdbe;
+namespace Community.CsharpSqlite {
+ using sqlite3_int64 = System.Int64;
- public partial class Sqlite3
- {
-/*
-** 2005 July 8
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains code associated with the ANALYZE command.
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
-**
-*************************************************************************
-*/
+ public partial class Sqlite3 {
+ /*
+ ** 2005 July 8
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains code associated with the ANALYZE command.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
+ **
+ *************************************************************************
+ */
#if !SQLITE_OMIT_ANALYZE
-//#include "sqliteInt.h"
-
-/*
-** This routine generates code that opens the sqlite_stat1 table for
-** writing with cursor iStatCur. If the library was built with the
-** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
-** opened for writing using cursor (iStatCur+1)
-**
-** If the sqlite_stat1 tables does not previously exist, it is created.
-** Similarly, if the sqlite_stat2 table does not exist and the library
-** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
-**
-** Argument zWhere may be a pointer to a buffer containing a table name,
-** or it may be a NULL pointer. If it is not NULL, then all entries in
-** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
-** with the named table are deleted. If zWhere==0, then code is generated
-** to delete all stat table entries.
-*/
-public struct _aTable
-{
- public string zName;
- public string zCols;
- public _aTable( string zName, string zCols )
- {
- this.zName = zName;
- this.zCols = zCols;
- }
-};
-static _aTable[] aTable = new _aTable[]{
+ //#include "sqliteInt.h"
+
+ /*
+ ** This routine generates code that opens the sqlite_stat1 table for
+ ** writing with cursor iStatCur. If the library was built with the
+ ** SQLITE_ENABLE_STAT2 macro defined, then the sqlite_stat2 table is
+ ** opened for writing using cursor (iStatCur+1)
+ **
+ ** If the sqlite_stat1 tables does not previously exist, it is created.
+ ** Similarly, if the sqlite_stat2 table does not exist and the library
+ ** is compiled with SQLITE_ENABLE_STAT2 defined, it is created.
+ **
+ ** Argument zWhere may be a pointer to a buffer containing a table name,
+ ** or it may be a NULL pointer. If it is not NULL, then all entries in
+ ** the sqlite_stat1 and (if applicable) sqlite_stat2 tables associated
+ ** with the named table are deleted. If zWhere==0, then code is generated
+ ** to delete all stat table entries.
+ */
+ public struct _aTable {
+ public string zName;
+ public string zCols;
+ public _aTable(string zName, string zCols) {
+ this.zName = zName;
+ this.zCols = zCols;
+ }
+ };
+ static _aTable[] aTable = new _aTable[]{
new _aTable( "sqlite_stat1", "tbl,idx,stat" ),
#if SQLITE_ENABLE_STAT2
new _aTable( "sqlite_stat2", "tbl,idx,sampleno,sample" ),
#endif
};
-static void openStatTable(
-Parse pParse, /* Parsing context */
-int iDb, /* The database we are looking in */
-int iStatCur, /* Open the sqlite_stat1 table on this cursor */
-string zWhere, /* Delete entries for this table or index */
-string zWhereType /* Either "tbl" or "idx" */
-)
-{
- int[] aRoot = new int[] { 0, 0 };
- u8[] aCreateTbl = new u8[] { 0, 0 };
-
- int i;
- sqlite3 db = pParse.db;
- Db pDb;
- Vdbe v = sqlite3GetVdbe( pParse );
-
- if ( v == null )
- return;
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
- Debug.Assert( sqlite3VdbeDb( v ) == db );
- pDb = db.aDb[iDb];
-
- for ( i = 0; i < ArraySize( aTable ); i++ )
- {
- string zTab = aTable[i].zName;
- Table pStat;
- if ( ( pStat = sqlite3FindTable( db, zTab, pDb.zName ) ) == null )
- {
- /* The sqlite_stat[12] table does not exist. Create it. Note that a
- ** side-effect of the CREATE TABLE statement is to leave the rootpage
- ** of the new table in register pParse.regRoot. This is important
- ** because the OpenWrite opcode below will be needing it. */
- sqlite3NestedParse( pParse,
- "CREATE TABLE %Q.%s(%s)", pDb.zName, zTab, aTable[i].zCols
- );
- aRoot[i] = pParse.regRoot;
- aCreateTbl[i] = 1;
- }
- else
- {
- /* The table already exists. If zWhere is not NULL, delete all entries
- ** associated with the table zWhere. If zWhere is NULL, delete the
- ** entire contents of the table. */
- aRoot[i] = pStat.tnum;
- sqlite3TableLock( pParse, iDb, aRoot[i], 1, zTab );
- if ( !String.IsNullOrEmpty( zWhere ) )
- {
- sqlite3NestedParse( pParse,
- "DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere
- );
- }
- else
- {
- /* The sqlite_stat[12] table already exists. Delete all rows. */
- sqlite3VdbeAddOp2( v, OP_Clear, aRoot[i], iDb );
- }
- }
- }
+ static void openStatTable(
+ Parse pParse, /* Parsing context */
+ int iDb, /* The database we are looking in */
+ int iStatCur, /* Open the sqlite_stat1 table on this cursor */
+ string zWhere, /* Delete entries for this table or index */
+ string zWhereType /* Either "tbl" or "idx" */
+ ) {
+ int[] aRoot = new int[] { 0, 0 };
+ u8[] aCreateTbl = new u8[] { 0, 0 };
+
+ int i;
+ sqlite3 db = pParse.db;
+ Db pDb;
+ Vdbe v = sqlite3GetVdbe(pParse);
+
+ if (v == null)
+ return;
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
+ Debug.Assert(sqlite3VdbeDb(v) == db);
+ pDb = db.aDb[iDb];
+
+ for (i = 0; i < ArraySize(aTable); i++) {
+ string zTab = aTable[i].zName;
+ Table pStat;
+ if ((pStat = sqlite3FindTable(db, zTab, pDb.zName)) == null) {
+ /* The sqlite_stat[12] table does not exist. Create it. Note that a
+ ** side-effect of the CREATE TABLE statement is to leave the rootpage
+ ** of the new table in register pParse.regRoot. This is important
+ ** because the OpenWrite opcode below will be needing it. */
+ sqlite3NestedParse(pParse,
+ "CREATE TABLE %Q.%s(%s)", pDb.zName, zTab, aTable[i].zCols
+ );
+ aRoot[i] = pParse.regRoot;
+ aCreateTbl[i] = 1;
+ } else {
+ /* The table already exists. If zWhere is not NULL, delete all entries
+ ** associated with the table zWhere. If zWhere is NULL, delete the
+ ** entire contents of the table. */
+ aRoot[i] = pStat.tnum;
+ sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
+ if (!String.IsNullOrEmpty(zWhere)) {
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.%s WHERE %s=%Q", pDb.zName, zTab, zWhereType, zWhere
+ );
+ } else {
+ /* The sqlite_stat[12] table already exists. Delete all rows. */
+ sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
+ }
+ }
+ }
- /* Open the sqlite_stat[12] tables for writing. */
- for ( i = 0; i < ArraySize( aTable ); i++ )
- {
- sqlite3VdbeAddOp3( v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb );
- sqlite3VdbeChangeP4( v, -1, 3, P4_INT32 );
- sqlite3VdbeChangeP5( v, aCreateTbl[i] );
- }
-}
+ /* Open the sqlite_stat[12] tables for writing. */
+ for (i = 0; i < ArraySize(aTable); i++) {
+ sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur + i, aRoot[i], iDb);
+ sqlite3VdbeChangeP4(v, -1, 3, P4_INT32);
+ sqlite3VdbeChangeP5(v, aCreateTbl[i]);
+ }
+ }
-/*
-** Generate code to do an analysis of all indices associated with
-** a single table.
-*/
-static void analyzeOneTable(
-Parse pParse, /* Parser context */
-Table pTab, /* Table whose indices are to be analyzed */
-Index pOnlyIdx, /* If not NULL, only analyze this one index */
-int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
-int iMem /* Available memory locations begin here */
-)
-{
- sqlite3 db = pParse.db; /* Database handle */
- Index pIdx; /* An index to being analyzed */
- int iIdxCur; /* Cursor open on index being analyzed */
- Vdbe v; /* The virtual machine being built up */
- int i; /* Loop counter */
- int topOfLoop; /* The top of the loop */
- int endOfLoop; /* The end of the loop */
- int jZeroRows = -1; /* Jump from here if number of rows is zero */
- int iDb; /* Index of database containing pTab */
- int regTabname = iMem++; /* Register containing table name */
- int regIdxname = iMem++; /* Register containing index name */
- int regSampleno = iMem++; /* Register containing next sample number */
- int regCol = iMem++; /* Content of a column analyzed table */
- int regRec = iMem++; /* Register holding completed record */
- int regTemp = iMem++; /* Temporary use register */
- int regRowid = iMem++; /* Rowid for the inserted record */
+ /*
+ ** Generate code to do an analysis of all indices associated with
+ ** a single table.
+ */
+ static void analyzeOneTable(
+ Parse pParse, /* Parser context */
+ Table pTab, /* Table whose indices are to be analyzed */
+ Index pOnlyIdx, /* If not NULL, only analyze this one index */
+ int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
+ int iMem /* Available memory locations begin here */
+ ) {
+ sqlite3 db = pParse.db; /* Database handle */
+ Index pIdx; /* An index to being analyzed */
+ int iIdxCur; /* Cursor open on index being analyzed */
+ Vdbe v; /* The virtual machine being built up */
+ int i; /* Loop counter */
+ int topOfLoop; /* The top of the loop */
+ int endOfLoop; /* The end of the loop */
+ int jZeroRows = -1; /* Jump from here if number of rows is zero */
+ int iDb; /* Index of database containing pTab */
+ int regTabname = iMem++; /* Register containing table name */
+ int regIdxname = iMem++; /* Register containing index name */
+ int regSampleno = iMem++; /* Register containing next sample number */
+ int regCol = iMem++; /* Content of a column analyzed table */
+ int regRec = iMem++; /* Register holding completed record */
+ int regTemp = iMem++; /* Temporary use register */
+ int regRowid = iMem++; /* Rowid for the inserted record */
#if SQLITE_ENABLE_STAT2
int addr = 0; /* Instruction address */
@@ -173,25 +157,22 @@ int iMem /* Available memory locations begin here */
int regFirst = iMem++; /* Index of first sample to record */
#endif
- v = sqlite3GetVdbe( pParse );
- if ( v == null || NEVER( pTab == null ) )
- {
- return;
- }
- if ( pTab.tnum == 0 )
- {
- /* Do not gather statistics on views or virtual tables */
- return;
- }
- if ( pTab.zName.StartsWith( "sqlite_", StringComparison.OrdinalIgnoreCase ) )
- {
- /* Do not gather statistics on system tables */
- return;
- }
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
- iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
- Debug.Assert( iDb >= 0 );
- Debug.Assert( sqlite3SchemaMutexHeld(db, iDb, null) );
+ v = sqlite3GetVdbe(pParse);
+ if (v == null || NEVER(pTab == null)) {
+ return;
+ }
+ if (pTab.tnum == 0) {
+ /* Do not gather statistics on views or virtual tables */
+ return;
+ }
+ if (pTab.zName.StartsWith("sqlite_", StringComparison.OrdinalIgnoreCase)) {
+ /* Do not gather statistics on system tables */
+ return;
+ }
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(db));
+ iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
+ Debug.Assert(iDb >= 0);
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
#if !SQLITE_OMIT_AUTHORIZATION
if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab.zName, 0,
db.aDb[iDb].zName ) ){
@@ -199,33 +180,31 @@ int iMem /* Available memory locations begin here */
}
#endif
- /* Establish a read-lock on the table at the shared-cache level. */
- sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName );
-
- iIdxCur = pParse.nTab++;
- sqlite3VdbeAddOp4( v, OP_String8, 0, regTabname, 0, pTab.zName, 0 );
- for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- int nCol;
- KeyInfo pKey;
- if ( pOnlyIdx != null && pOnlyIdx != pIdx )
- continue;
- nCol = pIdx.nColumn;
- pKey = sqlite3IndexKeyinfo( pParse, pIdx );
-
- if ( iMem + 1 + ( nCol * 2 ) > pParse.nMem )
- {
- pParse.nMem = iMem + 1 + ( nCol * 2 );
- }
+ /* Establish a read-lock on the table at the shared-cache level. */
+ sqlite3TableLock(pParse, iDb, pTab.tnum, 0, pTab.zName);
+
+ iIdxCur = pParse.nTab++;
+ sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab.zName, 0);
+ for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ int nCol;
+ KeyInfo pKey;
+ if (pOnlyIdx != null && pOnlyIdx != pIdx)
+ continue;
+ nCol = pIdx.nColumn;
+ pKey = sqlite3IndexKeyinfo(pParse, pIdx);
+
+ if (iMem + 1 + (nCol * 2) > pParse.nMem) {
+ pParse.nMem = iMem + 1 + (nCol * 2);
+ }
- /* Open a cursor to the index to be analyzed. */
- Debug.Assert( iDb == sqlite3SchemaToIndex( db, pIdx.pSchema ) );
- sqlite3VdbeAddOp4( v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb,
- pKey, P4_KEYINFO_HANDOFF );
- VdbeComment( v, "%s", pIdx.zName );
+ /* Open a cursor to the index to be analyzed. */
+ Debug.Assert(iDb == sqlite3SchemaToIndex(db, pIdx.pSchema));
+ sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx.tnum, iDb,
+ pKey, P4_KEYINFO_HANDOFF);
+ VdbeComment(v, "%s", pIdx.zName);
- /* Populate the registers containing the index names. */
- sqlite3VdbeAddOp4( v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0 );
+ /* Populate the registers containing the index names. */
+ sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx.zName, 0);
#if SQLITE_ENABLE_STAT2
@@ -254,44 +233,40 @@ int iMem /* Available memory locations begin here */
sqlite3VdbeAddOp2( v, OP_Copy, regFirst, regSamplerecno );
#endif
- /* The block of memory cells initialized here is used as follows.
-**
-** iMem:
-** The total number of rows in the table.
-**
-** iMem+1 .. iMem+nCol:
-** Number of distinct entries in index considering the
-** left-most N columns only, where N is between 1 and nCol,
-** inclusive.
-**
-** iMem+nCol+1 .. Mem+2*nCol:
-** Previous value of indexed columns, from left to right.
-**
-** Cells iMem through iMem+nCol are initialized to 0. The others are
-** initialized to contain an SQL NULL.
-*/
- for ( i = 0; i <= nCol; i++ )
- {
- sqlite3VdbeAddOp2( v, OP_Integer, 0, iMem + i );
- }
- for ( i = 0; i < nCol; i++ )
- {
- sqlite3VdbeAddOp2( v, OP_Null, 0, iMem + nCol + i + 1 );
- }
-
- /* Start the analysis loop. This loop runs through all the entries in
- ** the index b-tree. */
- endOfLoop = sqlite3VdbeMakeLabel( v );
- sqlite3VdbeAddOp2( v, OP_Rewind, iIdxCur, endOfLoop );
- topOfLoop = sqlite3VdbeCurrentAddr( v );
- sqlite3VdbeAddOp2( v, OP_AddImm, iMem, 1 );
+ /* The block of memory cells initialized here is used as follows.
+ **
+ ** iMem:
+ ** The total number of rows in the table.
+ **
+ ** iMem+1 .. iMem+nCol:
+ ** Number of distinct entries in index considering the
+ ** left-most N columns only, where N is between 1 and nCol,
+ ** inclusive.
+ **
+ ** iMem+nCol+1 .. Mem+2*nCol:
+ ** Previous value of indexed columns, from left to right.
+ **
+ ** Cells iMem through iMem+nCol are initialized to 0. The others are
+ ** initialized to contain an SQL NULL.
+ */
+ for (i = 0; i <= nCol; i++) {
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem + i);
+ }
+ for (i = 0; i < nCol; i++) {
+ sqlite3VdbeAddOp2(v, OP_Null, 0, iMem + nCol + i + 1);
+ }
- for ( i = 0; i < nCol; i++ )
- {
- sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, regCol );
- CollSeq pColl;
- if ( i == 0 )
- {
+ /* Start the analysis loop. This loop runs through all the entries in
+ ** the index b-tree. */
+ endOfLoop = sqlite3VdbeMakeLabel(v);
+ sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
+ topOfLoop = sqlite3VdbeCurrentAddr(v);
+ sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
+
+ for (i = 0; i < nCol; i++) {
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
+ CollSeq pColl;
+ if (i == 0) {
#if SQLITE_ENABLE_STAT2
/* Check if the record that cursor iIdxCur points to contains a
** value that should be stored in the sqlite_stat2 table. If so,
@@ -323,353 +298,307 @@ int iMem /* Available memory locations begin here */
sqlite3VdbeAddOp2( v, OP_AddImm, regRecno, 1 );
#endif
- /* Always record the very first row */
- sqlite3VdbeAddOp1( v, OP_IfNot, iMem + 1 );
- }
- Debug.Assert( pIdx.azColl != null );
- Debug.Assert( pIdx.azColl[i] != null );
- pColl = sqlite3LocateCollSeq( pParse, pIdx.azColl[i] );
- sqlite3VdbeAddOp4( v, OP_Ne, regCol, 0, iMem + nCol + i + 1,
- pColl, P4_COLLSEQ );
- sqlite3VdbeChangeP5( v, SQLITE_NULLEQ );
- }
- //if( db.mallocFailed ){
- // /* If a malloc failure has occurred, then the result of the expression
- // ** passed as the second argument to the call to sqlite3VdbeJumpHere()
- // ** below may be negative. Which causes an Debug.Assert() to fail (or an
- // ** out-of-bounds write if SQLITE_DEBUG is not defined). */
- // return;
- //}
- sqlite3VdbeAddOp2( v, OP_Goto, 0, endOfLoop );
- for ( i = 0; i < nCol; i++ )
- {
- int addr2 = sqlite3VdbeCurrentAddr( v ) - ( nCol * 2 );
- if ( i == 0 )
- {
- sqlite3VdbeJumpHere( v, addr2 - 1 ); /* Set jump dest for the OP_IfNot */
- }
- sqlite3VdbeJumpHere( v, addr2 ); /* Set jump dest for the OP_Ne */
- sqlite3VdbeAddOp2( v, OP_AddImm, iMem + i + 1, 1 );
- sqlite3VdbeAddOp3( v, OP_Column, iIdxCur, i, iMem + nCol + i + 1 );
- }
-
- /* End of the analysis loop. */
- sqlite3VdbeResolveLabel( v, endOfLoop );
- sqlite3VdbeAddOp2( v, OP_Next, iIdxCur, topOfLoop );
- sqlite3VdbeAddOp1( v, OP_Close, iIdxCur );
-
- /* Store the results in sqlite_stat1.
- **
- ** The result is a single row of the sqlite_stat1 table. The first
- ** two columns are the names of the table and index. The third column
- ** is a string composed of a list of integer statistics about the
- ** index. The first integer in the list is the total number of entries
- ** in the index. There is one additional integer in the list for each
- ** column of the table. This additional integer is a guess of how many
- ** rows of the table the index will select. If D is the count of distinct
- ** values and K is the total number of rows, then the integer is computed
- ** as:
- **
- ** I = (K+D-1)/D
- **
- ** If K==0 then no entry is made into the sqlite_stat1 table.
- ** If K>0 then it is always the case the D>0 so division by zero
- ** is never possible.
- */
- sqlite3VdbeAddOp2( v, OP_SCopy, iMem, regSampleno );
- if ( jZeroRows < 0 )
- {
- jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, iMem );
- }
- for ( i = 0; i < nCol; i++ )
- {
- sqlite3VdbeAddOp4( v, OP_String8, 0, regTemp, 0, " ", 0 );
- sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno );
- sqlite3VdbeAddOp3( v, OP_Add, iMem, iMem + i + 1, regTemp );
- sqlite3VdbeAddOp2( v, OP_AddImm, regTemp, -1 );
- sqlite3VdbeAddOp3( v, OP_Divide, iMem + i + 1, regTemp, regTemp );
- sqlite3VdbeAddOp1( v, OP_ToInt, regTemp );
- sqlite3VdbeAddOp3( v, OP_Concat, regTemp, regSampleno, regSampleno );
- }
- sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 );
- sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid );
- sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid );
- sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
- }
-
- /* If the table has no indices, create a single sqlite_stat1 entry
- ** containing NULL as the index name and the row count as the content.
- */
- if ( pTab.pIndex == null )
- {
- sqlite3VdbeAddOp3( v, OP_OpenRead, iIdxCur, pTab.tnum, iDb );
- VdbeComment( v, "%s", pTab.zName );
- sqlite3VdbeAddOp2( v, OP_Count, iIdxCur, regSampleno );
- sqlite3VdbeAddOp1( v, OP_Close, iIdxCur );
- jZeroRows = sqlite3VdbeAddOp1( v, OP_IfNot, regSampleno );
- }
- else
- {
- sqlite3VdbeJumpHere( v, jZeroRows );
- jZeroRows = sqlite3VdbeAddOp0( v, OP_Goto );
- }
- sqlite3VdbeAddOp2( v, OP_Null, 0, regIdxname );
- sqlite3VdbeAddOp4( v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0 );
- sqlite3VdbeAddOp2( v, OP_NewRowid, iStatCur, regRowid );
- sqlite3VdbeAddOp3( v, OP_Insert, iStatCur, regRec, regRowid );
- sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
- if ( pParse.nMem < regRec )
- pParse.nMem = regRec;
- sqlite3VdbeJumpHere( v, jZeroRows );
-}
-
-/*
-** Generate code that will cause the most recent index analysis to
-** be loaded into internal hash tables where is can be used.
-*/
-static void loadAnalysis( Parse pParse, int iDb )
-{
- Vdbe v = sqlite3GetVdbe( pParse );
- if ( v != null )
- {
- sqlite3VdbeAddOp1( v, OP_LoadAnalysis, iDb );
- }
-}
-
-/*
-** Generate code that will do an analysis of an entire database
-*/
-static void analyzeDatabase( Parse pParse, int iDb )
-{
- sqlite3 db = pParse.db;
- Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */
- HashElem k;
- int iStatCur;
- int iMem;
-
- sqlite3BeginWriteOperation( pParse, 0, iDb );
- iStatCur = pParse.nTab;
- pParse.nTab += 2;
- openStatTable( pParse, iDb, iStatCur, null, null );
- iMem = pParse.nMem + 1;
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- //for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){
- for ( k = pSchema.tblHash.first; k != null; k = k.next )
- {
- Table pTab = (Table)k.data;// sqliteHashData( k );
- analyzeOneTable( pParse, pTab, null, iStatCur, iMem );
- }
- loadAnalysis( pParse, iDb );
-}
+ /* Always record the very first row */
+ sqlite3VdbeAddOp1(v, OP_IfNot, iMem + 1);
+ }
+ Debug.Assert(pIdx.azColl != null);
+ Debug.Assert(pIdx.azColl[i] != null);
+ pColl = sqlite3LocateCollSeq(pParse, pIdx.azColl[i]);
+ sqlite3VdbeAddOp4(v, OP_Ne, regCol, 0, iMem + nCol + i + 1,
+ pColl, P4_COLLSEQ);
+ sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
+ }
+ //if( db.mallocFailed ){
+ // /* If a malloc failure has occurred, then the result of the expression
+ // ** passed as the second argument to the call to sqlite3VdbeJumpHere()
+ // ** below may be negative. Which causes an Debug.Assert() to fail (or an
+ // ** out-of-bounds write if SQLITE_DEBUG is not defined). */
+ // return;
+ //}
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
+ for (i = 0; i < nCol; i++) {
+ int addr2 = sqlite3VdbeCurrentAddr(v) - (nCol * 2);
+ if (i == 0) {
+ sqlite3VdbeJumpHere(v, addr2 - 1); /* Set jump dest for the OP_IfNot */
+ }
+ sqlite3VdbeJumpHere(v, addr2); /* Set jump dest for the OP_Ne */
+ sqlite3VdbeAddOp2(v, OP_AddImm, iMem + i + 1, 1);
+ sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem + nCol + i + 1);
+ }
-/*
-** Generate code that will do an analysis of a single table in
-** a database. If pOnlyIdx is not NULL then it is a single index
-** in pTab that should be analyzed.
-*/
-static void analyzeTable( Parse pParse, Table pTab, Index pOnlyIdx)
-{
- int iDb;
- int iStatCur;
-
- Debug.Assert( pTab != null );
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
- iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
- sqlite3BeginWriteOperation( pParse, 0, iDb );
- iStatCur = pParse.nTab;
- pParse.nTab += 2;
- if ( pOnlyIdx != null )
- {
- openStatTable( pParse, iDb, iStatCur, pOnlyIdx.zName, "idx" );
- }
- else
- {
- openStatTable( pParse, iDb, iStatCur, pTab.zName, "tbl" );
- }
- analyzeOneTable( pParse, pTab, pOnlyIdx, iStatCur, pParse.nMem + 1 );
- loadAnalysis( pParse, iDb );
-}
+ /* End of the analysis loop. */
+ sqlite3VdbeResolveLabel(v, endOfLoop);
+ sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
+ sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
+
+ /* Store the results in sqlite_stat1.
+ **
+ ** The result is a single row of the sqlite_stat1 table. The first
+ ** two columns are the names of the table and index. The third column
+ ** is a string composed of a list of integer statistics about the
+ ** index. The first integer in the list is the total number of entries
+ ** in the index. There is one additional integer in the list for each
+ ** column of the table. This additional integer is a guess of how many
+ ** rows of the table the index will select. If D is the count of distinct
+ ** values and K is the total number of rows, then the integer is computed
+ ** as:
+ **
+ ** I = (K+D-1)/D
+ **
+ ** If K==0 then no entry is made into the sqlite_stat1 table.
+ ** If K>0 then it is always the case the D>0 so division by zero
+ ** is never possible.
+ */
+ sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regSampleno);
+ if (jZeroRows < 0) {
+ jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
+ }
+ for (i = 0; i < nCol; i++) {
+ sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
+ sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
+ sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem + i + 1, regTemp);
+ sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
+ sqlite3VdbeAddOp3(v, OP_Divide, iMem + i + 1, regTemp, regTemp);
+ sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
+ sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regSampleno, regSampleno);
+ }
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ }
-/*
-** Generate code for the ANALYZE command. The parser calls this routine
-** when it recognizes an ANALYZE command.
-**
-** ANALYZE -- 1
-** ANALYZE -- 2
-** ANALYZE ?.? -- 3
-**
-** Form 1 causes all indices in all attached databases to be analyzed.
-** Form 2 analyzes all indices the single database named.
-** Form 3 analyzes all indices associated with the named table.
-*/
-// OVERLOADS, so I don't need to rewrite parse.c
-static void sqlite3Analyze( Parse pParse, int null_2, int null_3 )
-{
- sqlite3Analyze( pParse, null, null );
-}
-static void sqlite3Analyze( Parse pParse, Token pName1, Token pName2 )
-{
- sqlite3 db = pParse.db;
- int iDb;
- int i;
- string z, zDb;
- Table pTab;
- Index pIdx;
- Token pTableName = null;
-
- /* Read the database schema. If an error occurs, leave an error message
- ** and code in pParse and return NULL. */
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
- if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
- {
- return;
- }
+ /* If the table has no indices, create a single sqlite_stat1 entry
+ ** containing NULL as the index name and the row count as the content.
+ */
+ if (pTab.pIndex == null) {
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pTab.tnum, iDb);
+ VdbeComment(v, "%s", pTab.zName);
+ sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regSampleno);
+ sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
+ jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regSampleno);
+ } else {
+ sqlite3VdbeJumpHere(v, jZeroRows);
+ jZeroRows = sqlite3VdbeAddOp0(v, OP_Goto);
+ }
+ sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regRec, "aaa", 0);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
+ sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ if (pParse.nMem < regRec)
+ pParse.nMem = regRec;
+ sqlite3VdbeJumpHere(v, jZeroRows);
+ }
- Debug.Assert( pName2 != null || pName1 == null );
- if ( pName1 == null )
- {
- /* Form 1: Analyze everything */
- for ( i = 0; i < db.nDb; i++ )
- {
- if ( i == 1 )
- continue; /* Do not analyze the TEMP database */
- analyzeDatabase( pParse, i );
- }
- }
- else if ( pName2.n == 0 )
- {
- /* Form 2: Analyze the database or table named */
- iDb = sqlite3FindDb( db, pName1 );
- if ( iDb >= 0 )
- {
- analyzeDatabase( pParse, iDb );
- }
- else
- {
- z = sqlite3NameFromToken( db, pName1 );
- if ( z != null )
- {
- if ( ( pIdx = sqlite3FindIndex( db, z, null ) ) != null )
- {
- analyzeTable( pParse, pIdx.pTable, pIdx );
+ /*
+ ** Generate code that will cause the most recent index analysis to
+ ** be loaded into internal hash tables where is can be used.
+ */
+ static void loadAnalysis(Parse pParse, int iDb) {
+ Vdbe v = sqlite3GetVdbe(pParse);
+ if (v != null) {
+ sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
+ }
}
- else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, null ) ) != null )
- {
- analyzeTable( pParse, pTab, null );
+
+ /*
+ ** Generate code that will do an analysis of an entire database
+ */
+ static void analyzeDatabase(Parse pParse, int iDb) {
+ sqlite3 db = pParse.db;
+ Schema pSchema = db.aDb[iDb].pSchema; /* Schema of database iDb */
+ HashElem k;
+ int iStatCur;
+ int iMem;
+
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ iStatCur = pParse.nTab;
+ pParse.nTab += 2;
+ openStatTable(pParse, iDb, iStatCur, null, null);
+ iMem = pParse.nMem + 1;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ //for(k=sqliteHashFirst(pSchema.tblHash); k; k=sqliteHashNext(k)){
+ for (k = pSchema.tblHash.first; k != null; k = k.next) {
+ Table pTab = (Table)k.data;// sqliteHashData( k );
+ analyzeOneTable(pParse, pTab, null, iStatCur, iMem);
+ }
+ loadAnalysis(pParse, iDb);
}
- z = null;//sqlite3DbFree( db, z );
- }
- }
- }
- else
- {
- /* Form 3: Analyze the fully qualified table name */
- iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pTableName );
- if ( iDb >= 0 )
- {
- zDb = db.aDb[iDb].zName;
- z = sqlite3NameFromToken( db, pTableName );
- if ( z != null )
- {
- if ( ( pIdx = sqlite3FindIndex( db, z, zDb ) ) != null )
- {
- analyzeTable( pParse, pIdx.pTable, pIdx );
+
+ /*
+ ** Generate code that will do an analysis of a single table in
+ ** a database. If pOnlyIdx is not NULL then it is a single index
+ ** in pTab that should be analyzed.
+ */
+ static void analyzeTable(Parse pParse, Table pTab, Index pOnlyIdx) {
+ int iDb;
+ int iStatCur;
+
+ Debug.Assert(pTab != null);
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
+ iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ iStatCur = pParse.nTab;
+ pParse.nTab += 2;
+ if (pOnlyIdx != null) {
+ openStatTable(pParse, iDb, iStatCur, pOnlyIdx.zName, "idx");
+ } else {
+ openStatTable(pParse, iDb, iStatCur, pTab.zName, "tbl");
+ }
+ analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur, pParse.nMem + 1);
+ loadAnalysis(pParse, iDb);
}
- else if ( ( pTab = sqlite3LocateTable( pParse, 0, z, zDb ) ) != null )
- {
- analyzeTable( pParse, pTab, null );
+
+ /*
+ ** Generate code for the ANALYZE command. The parser calls this routine
+ ** when it recognizes an ANALYZE command.
+ **
+ ** ANALYZE -- 1
+ ** ANALYZE -- 2
+ ** ANALYZE ?.? -- 3
+ **
+ ** Form 1 causes all indices in all attached databases to be analyzed.
+ ** Form 2 analyzes all indices the single database named.
+ ** Form 3 analyzes all indices associated with the named table.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static void sqlite3Analyze(Parse pParse, int null_2, int null_3) {
+ sqlite3Analyze(pParse, null, null);
}
- z = null; //sqlite3DbFree( db, z );
- }
- }
- }
-}
+ static void sqlite3Analyze(Parse pParse, Token pName1, Token pName2) {
+ sqlite3 db = pParse.db;
+ int iDb;
+ int i;
+ string z, zDb;
+ Table pTab;
+ Index pIdx;
+ Token pTableName = null;
+
+ /* Read the database schema. If an error occurs, leave an error message
+ ** and code in pParse and return NULL. */
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(pParse.db));
+ if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
+ return;
+ }
-/*
-** Used to pass information from the analyzer reader through to the
-** callback routine.
-*/
-//typedef struct analysisInfo analysisInfo;
-public struct analysisInfo
-{
- public sqlite3 db;
- public string zDatabase;
-};
+ Debug.Assert(pName2 != null || pName1 == null);
+ if (pName1 == null) {
+ /* Form 1: Analyze everything */
+ for (i = 0; i < db.nDb; i++) {
+ if (i == 1)
+ continue; /* Do not analyze the TEMP database */
+ analyzeDatabase(pParse, i);
+ }
+ } else if (pName2.n == 0) {
+ /* Form 2: Analyze the database or table named */
+ iDb = sqlite3FindDb(db, pName1);
+ if (iDb >= 0) {
+ analyzeDatabase(pParse, iDb);
+ } else {
+ z = sqlite3NameFromToken(db, pName1);
+ if (z != null) {
+ if ((pIdx = sqlite3FindIndex(db, z, null)) != null) {
+ analyzeTable(pParse, pIdx.pTable, pIdx);
+ } else if ((pTab = sqlite3LocateTable(pParse, 0, z, null)) != null) {
+ analyzeTable(pParse, pTab, null);
+ }
+ z = null;//sqlite3DbFree( db, z );
+ }
+ }
+ } else {
+ /* Form 3: Analyze the fully qualified table name */
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, ref pTableName);
+ if (iDb >= 0) {
+ zDb = db.aDb[iDb].zName;
+ z = sqlite3NameFromToken(db, pTableName);
+ if (z != null) {
+ if ((pIdx = sqlite3FindIndex(db, z, zDb)) != null) {
+ analyzeTable(pParse, pIdx.pTable, pIdx);
+ } else if ((pTab = sqlite3LocateTable(pParse, 0, z, zDb)) != null) {
+ analyzeTable(pParse, pTab, null);
+ }
+ z = null; //sqlite3DbFree( db, z );
+ }
+ }
+ }
+ }
-/*
-** This callback is invoked once for each index when reading the
-** sqlite_stat1 table.
-**
-** argv[0] = name of the table
-** argv[1] = name of the index (might be NULL)
-** argv[2] = results of analysis - on integer for each column
-**
-** Entries for which argv[1]==NULL simply record the number of rows in
-** the table.
-*/
-static int analysisLoader( object pData, sqlite3_int64 argc, object Oargv, object NotUsed )
-{
- string[] argv = (string[])Oargv;
- analysisInfo pInfo = (analysisInfo)pData;
- Index pIndex;
- Table pTable;
- int i, c, n;
- int v;
- string z;
-
- Debug.Assert( argc == 3 );
- UNUSED_PARAMETER2( NotUsed, argc );
- if ( argv == null || argv[0] == null || argv[2] == null )
- {
- return 0;
- }
- pTable = sqlite3FindTable( pInfo.db, argv[0], pInfo.zDatabase );
- if ( pTable == null )
- {
- return 0;
- }
- if ( !String.IsNullOrEmpty( argv[1] ) )
- {
- pIndex = sqlite3FindIndex( pInfo.db, argv[1], pInfo.zDatabase );
- }
- else
- {
- pIndex = null;
- }
+ /*
+ ** Used to pass information from the analyzer reader through to the
+ ** callback routine.
+ */
+ //typedef struct analysisInfo analysisInfo;
+ public struct analysisInfo {
+ public sqlite3 db;
+ public string zDatabase;
+ };
+
+ /*
+ ** This callback is invoked once for each index when reading the
+ ** sqlite_stat1 table.
+ **
+ ** argv[0] = name of the table
+ ** argv[1] = name of the index (might be NULL)
+ ** argv[2] = results of analysis - on integer for each column
+ **
+ ** Entries for which argv[1]==NULL simply record the number of rows in
+ ** the table.
+ */
+ static int analysisLoader(object pData, sqlite3_int64 argc, object Oargv, object NotUsed) {
+ string[] argv = (string[])Oargv;
+ analysisInfo pInfo = (analysisInfo)pData;
+ Index pIndex;
+ Table pTable;
+ int i, c, n;
+ int v;
+ string z;
+
+ Debug.Assert(argc == 3);
+ UNUSED_PARAMETER2(NotUsed, argc);
+ if (argv == null || argv[0] == null || argv[2] == null) {
+ return 0;
+ }
+ pTable = sqlite3FindTable(pInfo.db, argv[0], pInfo.zDatabase);
+ if (pTable == null) {
+ return 0;
+ }
+ if (!String.IsNullOrEmpty(argv[1])) {
+ pIndex = sqlite3FindIndex(pInfo.db, argv[1], pInfo.zDatabase);
+ } else {
+ pIndex = null;
+ }
- n = pIndex != null ? pIndex.nColumn : 0;
- z = argv[2];
- int zIndex = 0;
- for ( i = 0; z != null && i <= n; i++ )
- {
- v = 0;
- while ( zIndex < z.Length && ( c = z[zIndex] ) >= '0' && c <= '9' )
- {
- v = v * 10 + c - '0';
- zIndex++;
- }
- if ( i == 0 )
- pTable.nRowEst = (uint)v;
- if ( pIndex == null )
- break;
- pIndex.aiRowEst[i] = v;
- if ( zIndex < z.Length && z[zIndex] == ' ' )
- zIndex++;
- if ( string.Equals(z.Substring(zIndex), "unordered", StringComparison.Ordinal) )//memcmp( z, "unordered", 10 ) == 0 )
- {
- pIndex.bUnordered = 1;
- break;
- }
- }
- return 0;
-}
+ n = pIndex != null ? pIndex.nColumn : 0;
+ z = argv[2];
+ int zIndex = 0;
+ for (i = 0; z != null && i <= n; i++) {
+ v = 0;
+ while (zIndex < z.Length && (c = z[zIndex]) >= '0' && c <= '9') {
+ v = v * 10 + c - '0';
+ zIndex++;
+ }
+ if (i == 0)
+ pTable.nRowEst = (uint)v;
+ if (pIndex == null)
+ break;
+ pIndex.aiRowEst[i] = v;
+ if (zIndex < z.Length && z[zIndex] == ' ')
+ zIndex++;
+ if (string.Equals(z.Substring(zIndex), "unordered", StringComparison.Ordinal))//memcmp( z, "unordered", 10 ) == 0 )
+ {
+ pIndex.bUnordered = 1;
+ break;
+ }
+ }
+ return 0;
+ }
-/*
-** If the Index.aSample variable is not NULL, delete the aSample[] array
-** and its contents.
-*/
-static void sqlite3DeleteIndexSamples( sqlite3 db, Index pIdx )
-{
+ /*
+ ** If the Index.aSample variable is not NULL, delete the aSample[] array
+ ** and its contents.
+ */
+ static void sqlite3DeleteIndexSamples(sqlite3 db, Index pIdx) {
#if SQLITE_ENABLE_STAT2
if ( pIdx.aSample != null )
{
@@ -686,75 +615,72 @@ static void sqlite3DeleteIndexSamples( sqlite3 db, Index pIdx )
sqlite3DbFree( db, ref pIdx.aSample );
}
#else
-UNUSED_PARAMETER(db);
-UNUSED_PARAMETER( pIdx );
+ UNUSED_PARAMETER(db);
+ UNUSED_PARAMETER(pIdx);
#endif
-}
+ }
-/*
-** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
-** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
-** arrays. The contents of sqlite_stat2 are used to populate the
-** Index.aSample[] arrays.
-**
-** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
-** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
-** during compilation and the sqlite_stat2 table is present, no data is
-** read from it.
-**
-** If SQLITE_ENABLE_STAT2 was defined during compilation and the
-** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
-** returned. However, in this case, data is read from the sqlite_stat1
-** table (if it is present) before returning.
-**
-** If an OOM error occurs, this function always sets db.mallocFailed.
-** This means if the caller does not care about other errors, the return
-** code may be ignored.
-*/
-static int sqlite3AnalysisLoad( sqlite3 db, int iDb )
-{
- analysisInfo sInfo;
- HashElem i;
- string zSql;
- int rc;
-
- Debug.Assert( iDb >= 0 && iDb < db.nDb );
- Debug.Assert( db.aDb[iDb].pBt != null );
- /* Clear any prior statistics */
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- //for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){
- for ( i = db.aDb[iDb].pSchema.idxHash.first; i != null; i = i.next )
- {
- Index pIdx = (Index)i.data;// sqliteHashData( i );
- sqlite3DefaultRowEst( pIdx );
- sqlite3DeleteIndexSamples( db, pIdx );
- pIdx.aSample = null;
- }
+ /*
+ ** Load the content of the sqlite_stat1 and sqlite_stat2 tables. The
+ ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
+ ** arrays. The contents of sqlite_stat2 are used to populate the
+ ** Index.aSample[] arrays.
+ **
+ ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
+ ** is returned. In this case, even if SQLITE_ENABLE_STAT2 was defined
+ ** during compilation and the sqlite_stat2 table is present, no data is
+ ** read from it.
+ **
+ ** If SQLITE_ENABLE_STAT2 was defined during compilation and the
+ ** sqlite_stat2 table is not present in the database, SQLITE_ERROR is
+ ** returned. However, in this case, data is read from the sqlite_stat1
+ ** table (if it is present) before returning.
+ **
+ ** If an OOM error occurs, this function always sets db.mallocFailed.
+ ** This means if the caller does not care about other errors, the return
+ ** code may be ignored.
+ */
+ static int sqlite3AnalysisLoad(sqlite3 db, int iDb) {
+ analysisInfo sInfo;
+ HashElem i;
+ string zSql;
+ int rc;
+
+ Debug.Assert(iDb >= 0 && iDb < db.nDb);
+ Debug.Assert(db.aDb[iDb].pBt != null);
+ /* Clear any prior statistics */
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ //for(i=sqliteHashFirst(&db.aDb[iDb].pSchema.idxHash);i;i=sqliteHashNext(i)){
+ for (i = db.aDb[iDb].pSchema.idxHash.first; i != null; i = i.next) {
+ Index pIdx = (Index)i.data;// sqliteHashData( i );
+ sqlite3DefaultRowEst(pIdx);
+ sqlite3DeleteIndexSamples(db, pIdx);
+ pIdx.aSample = null;
+ }
- /* Check to make sure the sqlite_stat1 table exists */
- sInfo.db = db;
- sInfo.zDatabase = db.aDb[iDb].zName;
- if ( sqlite3FindTable( db, "sqlite_stat1", sInfo.zDatabase ) == null )
- {
- return SQLITE_ERROR;
- }
+ /* Check to make sure the sqlite_stat1 table exists */
+ sInfo.db = db;
+ sInfo.zDatabase = db.aDb[iDb].zName;
+ if (sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase) == null) {
+ return SQLITE_ERROR;
+ }
- /* Load new statistics out of the sqlite_stat1 table */
- zSql = sqlite3MPrintf( db,
- "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase );
- //if ( zSql == null )
- //{
- // rc = SQLITE_NOMEM;
- //}
- //else
- {
- rc = sqlite3_exec( db, zSql, (dxCallback)analysisLoader, sInfo, 0 );
- sqlite3DbFree( db, ref zSql );
- }
+ /* Load new statistics out of the sqlite_stat1 table */
+ zSql = sqlite3MPrintf(db,
+ "SELECT tbl, idx, stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
+ //if ( zSql == null )
+ //{
+ // rc = SQLITE_NOMEM;
+ //}
+ //else
+ {
+ rc = sqlite3_exec(db, zSql, (dxCallback)analysisLoader, sInfo, 0);
+ sqlite3DbFree(db, ref zSql);
+ }
- /* Load the statistics from the sqlite_stat2 table. */
+ /* Load the statistics from the sqlite_stat2 table. */
#if SQLITE_ENABLE_STAT2
if ( rc == SQLITE_OK && null == sqlite3FindTable( db, "sqlite_stat2", sInfo.zDatabase ) )
{
@@ -855,12 +781,12 @@ static int sqlite3AnalysisLoad( sqlite3 db, int iDb )
}
#endif
- //if( rc==SQLITE_NOMEM ){
- // db.mallocFailed = 1;
- //}
- return rc;
-}
+ //if( rc==SQLITE_NOMEM ){
+ // db.mallocFailed = 1;
+ //}
+ return rc;
+ }
#endif // * SQLITE_OMIT_ANALYZE */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/attach_c.cs b/Src/IronPython.SQLite/c#sqlite/attach_c.cs
index ede667540..16149bd60 100644
--- a/Src/IronPython.SQLite/c#sqlite/attach_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/attach_c.cs
@@ -3,214 +3,195 @@
using System.Text;
using u8 = System.Byte;
-using u32 = System.UInt32;
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
-
- public partial class Sqlite3
- {
-/*
-** 2003 April 6
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains code used to implement the ATTACH and DETACH commands.
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
-**
-*************************************************************************
-*/
-//#include "sqliteInt.h"
+namespace Community.CsharpSqlite {
+ using sqlite3_value = Sqlite3.Mem;
+
+ public partial class Sqlite3 {
+ /*
+ ** 2003 April 6
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains code used to implement the ATTACH and DETACH commands.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
#if !SQLITE_OMIT_ATTACH
-/*
-** Resolve an expression that was part of an ATTACH or DETACH statement. This
-** is slightly different from resolving a normal SQL expression, because simple
-** identifiers are treated as strings, not possible column names or aliases.
-**
-** i.e. if the parser sees:
-**
-** ATTACH DATABASE abc AS def
-**
-** it treats the two expressions as literal strings 'abc' and 'def' instead of
-** looking for columns of the same name.
-**
-** This only applies to the root node of pExpr, so the statement:
-**
-** ATTACH DATABASE abc||def AS 'db2'
-**
-** will fail because neither abc or def can be resolved.
-*/
-static int resolveAttachExpr( NameContext pName, Expr pExpr )
-{
- int rc = SQLITE_OK;
- if ( pExpr != null )
- {
- if ( pExpr.op != TK_ID )
- {
- rc = sqlite3ResolveExprNames( pName, ref pExpr );
- if ( rc == SQLITE_OK && sqlite3ExprIsConstant( pExpr ) == 0 )
- {
- sqlite3ErrorMsg( pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken );
- return SQLITE_ERROR;
- }
- }
- else
- {
- pExpr.op = TK_STRING;
- }
- }
- return rc;
-}
-
-/*
-** An SQL user-function registered to do the work of an ATTACH statement. The
-** three arguments to the function come directly from an attach statement:
-**
-** ATTACH DATABASE x AS y KEY z
-**
-** SELECT sqlite_attach(x, y, z)
-**
-** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
-** third argument.
-*/
-static void attachFunc(
-sqlite3_context context,
-int NotUsed,
-sqlite3_value[] argv
-)
-{
- int i;
- int rc = 0;
- sqlite3 db = sqlite3_context_db_handle( context );
- string zName;
- string zFile;
- string zPath = "";
- string zErr = "";
- int flags;
-
- Db aNew = null;
- string zErrDyn = "";
- sqlite3_vfs pVfs = null;
-
- UNUSED_PARAMETER( NotUsed );
-
- zFile = argv[0].z != null && ( argv[0].z.Length > 0 ) && argv[0].flags != MEM_Null ? sqlite3_value_text( argv[0] ) : "";
- zName = argv[1].z != null && ( argv[1].z.Length > 0 ) && argv[1].flags != MEM_Null ? sqlite3_value_text( argv[1] ) : "";
- //if( zFile==null ) zFile = "";
- //if ( zName == null ) zName = "";
-
-
- /* Check for the following errors:
- **
- ** * Too many attached databases,
- ** * Transaction currently open
- ** * Specified database name already being used.
- */
- if ( db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2 )
- {
- zErrDyn = sqlite3MPrintf( db, "too many attached databases - max %d",
- db.aLimit[SQLITE_LIMIT_ATTACHED]
- );
- goto attach_error;
- }
- if ( 0 == db.autoCommit )
- {
- zErrDyn = sqlite3MPrintf( db, "cannot ATTACH database within transaction" );
- goto attach_error;
- }
- for ( i = 0; i < db.nDb; i++ )
- {
- string z = db.aDb[i].zName;
- Debug.Assert( z != null && zName != null );
- if ( z.Equals( zName, StringComparison.OrdinalIgnoreCase ) )
- {
- zErrDyn = sqlite3MPrintf( db, "database %s is already in use", zName );
- goto attach_error;
- }
- }
+ /*
+ ** Resolve an expression that was part of an ATTACH or DETACH statement. This
+ ** is slightly different from resolving a normal SQL expression, because simple
+ ** identifiers are treated as strings, not possible column names or aliases.
+ **
+ ** i.e. if the parser sees:
+ **
+ ** ATTACH DATABASE abc AS def
+ **
+ ** it treats the two expressions as literal strings 'abc' and 'def' instead of
+ ** looking for columns of the same name.
+ **
+ ** This only applies to the root node of pExpr, so the statement:
+ **
+ ** ATTACH DATABASE abc||def AS 'db2'
+ **
+ ** will fail because neither abc or def can be resolved.
+ */
+ static int resolveAttachExpr(NameContext pName, Expr pExpr) {
+ int rc = SQLITE_OK;
+ if (pExpr != null) {
+ if (pExpr.op != TK_ID) {
+ rc = sqlite3ResolveExprNames(pName, ref pExpr);
+ if (rc == SQLITE_OK && sqlite3ExprIsConstant(pExpr) == 0) {
+ sqlite3ErrorMsg(pName.pParse, "invalid name: \"%s\"", pExpr.u.zToken);
+ return SQLITE_ERROR;
+ }
+ } else {
+ pExpr.op = TK_STRING;
+ }
+ }
+ return rc;
+ }
- /* Allocate the new entry in the db.aDb[] array and initialise the schema
- ** hash tables.
- */
- /* Allocate the new entry in the db.aDb[] array and initialise the schema
- ** hash tables.
- */
- //if( db.aDb==db.aDbStatic ){
- // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
- // if( aNew==0 ) return;
- // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
- //}else {
- if ( db.aDb.Length <= db.nDb )
- Array.Resize( ref db.aDb, db.nDb + 1 );//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
- if ( db.aDb == null )
- return; // if( aNew==0 ) return;
- //}
- db.aDb[db.nDb] = new Db();//db.aDb = aNew;
- aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
- // memset(aNew, 0, sizeof(*aNew));
-
- /* Open the database file. If the btree is successfully opened, use
- ** it to obtain the database schema. At this point the schema may
- ** or may not be initialised.
- */
- flags = (int)db.openFlags;
- rc = sqlite3ParseUri( vfsList.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr );
- if ( rc != SQLITE_OK )
- {
- //if ( rc == SQLITE_NOMEM )
- //db.mallocFailed = 1;
- sqlite3_result_error( context, zErr, -1 );
- //sqlite3_free( zErr );
- return;
- }
- Debug.Assert( pVfs != null);
- flags |= SQLITE_OPEN_MAIN_DB;
- rc = sqlite3BtreeOpen( pVfs, zPath, db, ref aNew.pBt, 0, (int)flags );
- //sqlite3_free( zPath );
-
- db.nDb++;
- if ( rc == SQLITE_CONSTRAINT )
- {
- rc = SQLITE_ERROR;
- zErrDyn = sqlite3MPrintf( db, "database is already attached" );
- }
- else if ( rc == SQLITE_OK )
- {
- Pager pPager;
- aNew.pSchema = sqlite3SchemaGet( db, aNew.pBt );
- //if ( aNew.pSchema == null )
- //{
- // rc = SQLITE_NOMEM;
- //}
- //else
- if ( aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC( db ) )
- {
- zErrDyn = sqlite3MPrintf( db,
- "attached databases must use the same text encoding as main database" );
- rc = SQLITE_ERROR;
- }
- pPager = sqlite3BtreePager( aNew.pBt );
- sqlite3PagerLockingMode( pPager, db.dfltLockMode );
- sqlite3BtreeSecureDelete( aNew.pBt,
- sqlite3BtreeSecureDelete( db.aDb[0].pBt, -1 ) );
- }
- aNew.safety_level = 3;
- aNew.zName = zName;//sqlite3DbStrDup(db, zName);
- //if( rc==SQLITE_OK && aNew.zName==0 ){
- // rc = SQLITE_NOMEM;
- //}
+ /*
+ ** An SQL user-function registered to do the work of an ATTACH statement. The
+ ** three arguments to the function come directly from an attach statement:
+ **
+ ** ATTACH DATABASE x AS y KEY z
+ **
+ ** SELECT sqlite_attach(x, y, z)
+ **
+ ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
+ ** third argument.
+ */
+ static void attachFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] argv
+ ) {
+ int i;
+ int rc = 0;
+ sqlite3 db = sqlite3_context_db_handle(context);
+ string zName;
+ string zFile;
+ string zPath = "";
+ string zErr = "";
+ int flags;
+
+ Db aNew = null;
+ string zErrDyn = "";
+ sqlite3_vfs pVfs = null;
+
+ UNUSED_PARAMETER(NotUsed);
+
+ zFile = argv[0].z != null && (argv[0].z.Length > 0) && argv[0].flags != MEM_Null ? sqlite3_value_text(argv[0]) : "";
+ zName = argv[1].z != null && (argv[1].z.Length > 0) && argv[1].flags != MEM_Null ? sqlite3_value_text(argv[1]) : "";
+ //if( zFile==null ) zFile = "";
+ //if ( zName == null ) zName = "";
+
+
+ /* Check for the following errors:
+ **
+ ** * Too many attached databases,
+ ** * Transaction currently open
+ ** * Specified database name already being used.
+ */
+ if (db.nDb >= db.aLimit[SQLITE_LIMIT_ATTACHED] + 2) {
+ zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
+ db.aLimit[SQLITE_LIMIT_ATTACHED]
+ );
+ goto attach_error;
+ }
+ if (0 == db.autoCommit) {
+ zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
+ goto attach_error;
+ }
+ for (i = 0; i < db.nDb; i++) {
+ string z = db.aDb[i].zName;
+ Debug.Assert(z != null && zName != null);
+ if (z.Equals(zName, StringComparison.OrdinalIgnoreCase)) {
+ zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
+ goto attach_error;
+ }
+ }
+
+ /* Allocate the new entry in the db.aDb[] array and initialise the schema
+ ** hash tables.
+ */
+ /* Allocate the new entry in the db.aDb[] array and initialise the schema
+ ** hash tables.
+ */
+ //if( db.aDb==db.aDbStatic ){
+ // aNew = sqlite3DbMallocRaw(db, sizeof(db.aDb[0])*3 );
+ // if( aNew==0 ) return;
+ // memcpy(aNew, db.aDb, sizeof(db.aDb[0])*2);
+ //}else {
+ if (db.aDb.Length <= db.nDb)
+ Array.Resize(ref db.aDb, db.nDb + 1);//aNew = sqlite3DbRealloc(db, db.aDb, sizeof(db.aDb[0])*(db.nDb+1) );
+ if (db.aDb == null)
+ return; // if( aNew==0 ) return;
+ //}
+ db.aDb[db.nDb] = new Db();//db.aDb = aNew;
+ aNew = db.aDb[db.nDb];//memset(aNew, 0, sizeof(*aNew));
+ // memset(aNew, 0, sizeof(*aNew));
+
+ /* Open the database file. If the btree is successfully opened, use
+ ** it to obtain the database schema. At this point the schema may
+ ** or may not be initialised.
+ */
+ flags = (int)db.openFlags;
+ rc = sqlite3ParseUri(vfsList.zName, zFile, ref flags, ref pVfs, ref zPath, ref zErr);
+ if (rc != SQLITE_OK) {
+ //if ( rc == SQLITE_NOMEM )
+ //db.mallocFailed = 1;
+ sqlite3_result_error(context, zErr, -1);
+ //sqlite3_free( zErr );
+ return;
+ }
+ Debug.Assert(pVfs != null);
+ flags |= SQLITE_OPEN_MAIN_DB;
+ rc = sqlite3BtreeOpen(pVfs, zPath, db, ref aNew.pBt, 0, (int)flags);
+ //sqlite3_free( zPath );
+
+ db.nDb++;
+ if (rc == SQLITE_CONSTRAINT) {
+ rc = SQLITE_ERROR;
+ zErrDyn = sqlite3MPrintf(db, "database is already attached");
+ } else if (rc == SQLITE_OK) {
+ Pager pPager;
+ aNew.pSchema = sqlite3SchemaGet(db, aNew.pBt);
+ //if ( aNew.pSchema == null )
+ //{
+ // rc = SQLITE_NOMEM;
+ //}
+ //else
+ if (aNew.pSchema.file_format != 0 && aNew.pSchema.enc != ENC(db)) {
+ zErrDyn = sqlite3MPrintf(db,
+ "attached databases must use the same text encoding as main database");
+ rc = SQLITE_ERROR;
+ }
+ pPager = sqlite3BtreePager(aNew.pBt);
+ sqlite3PagerLockingMode(pPager, db.dfltLockMode);
+ sqlite3BtreeSecureDelete(aNew.pBt,
+ sqlite3BtreeSecureDelete(db.aDb[0].pBt, -1));
+ }
+ aNew.safety_level = 3;
+ aNew.zName = zName;//sqlite3DbStrDup(db, zName);
+ //if( rc==SQLITE_OK && aNew.zName==0 ){
+ // rc = SQLITE_NOMEM;
+ //}
#if SQLITE_HAS_CODEC
if ( rc == SQLITE_OK )
@@ -247,151 +228,136 @@ sqlite3_value[] argv
}
#endif
- /* If the file was opened successfully, read the schema for the new database.
-** If this fails, or if opening the file failed, then close the file and
-** remove the entry from the db.aDb[] array. i.e. put everything back the way
-** we found it.
-*/
- if ( rc == SQLITE_OK )
- {
- sqlite3BtreeEnterAll( db );
- rc = sqlite3Init( db, ref zErrDyn );
- sqlite3BtreeLeaveAll( db );
- }
- if ( rc != 0 )
- {
- int iDb = db.nDb - 1;
- Debug.Assert( iDb >= 2 );
- if ( db.aDb[iDb].pBt != null )
- {
- sqlite3BtreeClose( ref db.aDb[iDb].pBt );
- db.aDb[iDb].pBt = null;
- db.aDb[iDb].pSchema = null;
- }
- sqlite3ResetInternalSchema( db, -1 );
- db.nDb = iDb;
- if ( rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM )
- {
- //// db.mallocFailed = 1;
- sqlite3DbFree( db, ref zErrDyn );
- zErrDyn = sqlite3MPrintf( db, "out of memory" );
- }
- else if ( zErrDyn == "" )
- {
- zErrDyn = sqlite3MPrintf( db, "unable to open database: %s", zFile );
- }
- goto attach_error;
- }
-
- return;
-
-attach_error:
- /* Return an error if we get here */
- if ( zErrDyn != "" )
- {
- sqlite3_result_error( context, zErrDyn, -1 );
- sqlite3DbFree( db, ref zErrDyn );
- }
- if ( rc != 0 )
- sqlite3_result_error_code( context, rc );
-}
-
-/*
-** An SQL user-function registered to do the work of an DETACH statement. The
-** three arguments to the function come directly from a detach statement:
-**
-** DETACH DATABASE x
-**
-** SELECT sqlite_detach(x)
-*/
-static void detachFunc(
-sqlite3_context context,
-int NotUsed,
-sqlite3_value[] argv
-)
-{
- string zName = zName = argv[0].z != null && ( argv[0].z.Length > 0 ) ? sqlite3_value_text( argv[0] ) : "";//(sqlite3_value_text(argv[0]);
- sqlite3 db = sqlite3_context_db_handle( context );
- int i;
- Db pDb = null;
- StringBuilder zErr = new StringBuilder( 200 );
-
- UNUSED_PARAMETER( NotUsed );
-
- if ( zName == null )
- zName = "";
- for ( i = 0; i < db.nDb; i++ )
- {
- pDb = db.aDb[i];
- if ( pDb.pBt == null )
- continue;
- if ( pDb.zName.Equals( zName, StringComparison.OrdinalIgnoreCase ) )
- break;
- }
-
- if ( i >= db.nDb )
- {
- sqlite3_snprintf( 200, zErr, "no such database: %s", zName );
- goto detach_error;
- }
- if ( i < 2 )
- {
- sqlite3_snprintf( 200, zErr, "cannot detach database %s", zName );
- goto detach_error;
- }
- if ( 0 == db.autoCommit )
- {
- sqlite3_snprintf( 200, zErr,
- "cannot DETACH database within transaction" );
- goto detach_error;
- }
- if ( sqlite3BtreeIsInReadTrans( pDb.pBt ) || sqlite3BtreeIsInBackup( pDb.pBt ) )
- {
- sqlite3_snprintf( 200, zErr, "database %s is locked", zName );
- goto detach_error;
- }
+ /* If the file was opened successfully, read the schema for the new database.
+ ** If this fails, or if opening the file failed, then close the file and
+ ** remove the entry from the db.aDb[] array. i.e. put everything back the way
+ ** we found it.
+ */
+ if (rc == SQLITE_OK) {
+ sqlite3BtreeEnterAll(db);
+ rc = sqlite3Init(db, ref zErrDyn);
+ sqlite3BtreeLeaveAll(db);
+ }
+ if (rc != 0) {
+ int iDb = db.nDb - 1;
+ Debug.Assert(iDb >= 2);
+ if (db.aDb[iDb].pBt != null) {
+ sqlite3BtreeClose(ref db.aDb[iDb].pBt);
+ db.aDb[iDb].pBt = null;
+ db.aDb[iDb].pSchema = null;
+ }
+ sqlite3ResetInternalSchema(db, -1);
+ db.nDb = iDb;
+ if (rc == SQLITE_NOMEM || rc == SQLITE_IOERR_NOMEM) {
+ //// db.mallocFailed = 1;
+ sqlite3DbFree(db, ref zErrDyn);
+ zErrDyn = sqlite3MPrintf(db, "out of memory");
+ } else if (zErrDyn == "") {
+ zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
+ }
+ goto attach_error;
+ }
+
+ return;
+
+ attach_error:
+ /* Return an error if we get here */
+ if (zErrDyn != "") {
+ sqlite3_result_error(context, zErrDyn, -1);
+ sqlite3DbFree(db, ref zErrDyn);
+ }
+ if (rc != 0)
+ sqlite3_result_error_code(context, rc);
+ }
- sqlite3BtreeClose( ref pDb.pBt );
- pDb.pBt = null;
- pDb.pSchema = null;
- sqlite3ResetInternalSchema( db, -1 );
- return;
+ /*
+ ** An SQL user-function registered to do the work of an DETACH statement. The
+ ** three arguments to the function come directly from a detach statement:
+ **
+ ** DETACH DATABASE x
+ **
+ ** SELECT sqlite_detach(x)
+ */
+ static void detachFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] argv
+ ) {
+ string zName = zName = argv[0].z != null && (argv[0].z.Length > 0) ? sqlite3_value_text(argv[0]) : "";//(sqlite3_value_text(argv[0]);
+ sqlite3 db = sqlite3_context_db_handle(context);
+ int i;
+ Db pDb = null;
+ StringBuilder zErr = new StringBuilder(200);
+
+ UNUSED_PARAMETER(NotUsed);
+
+ if (zName == null)
+ zName = "";
+ for (i = 0; i < db.nDb; i++) {
+ pDb = db.aDb[i];
+ if (pDb.pBt == null)
+ continue;
+ if (pDb.zName.Equals(zName, StringComparison.OrdinalIgnoreCase))
+ break;
+ }
+
+ if (i >= db.nDb) {
+ sqlite3_snprintf(200, zErr, "no such database: %s", zName);
+ goto detach_error;
+ }
+ if (i < 2) {
+ sqlite3_snprintf(200, zErr, "cannot detach database %s", zName);
+ goto detach_error;
+ }
+ if (0 == db.autoCommit) {
+ sqlite3_snprintf(200, zErr,
+ "cannot DETACH database within transaction");
+ goto detach_error;
+ }
+ if (sqlite3BtreeIsInReadTrans(pDb.pBt) || sqlite3BtreeIsInBackup(pDb.pBt)) {
+ sqlite3_snprintf(200, zErr, "database %s is locked", zName);
+ goto detach_error;
+ }
+
+ sqlite3BtreeClose(ref pDb.pBt);
+ pDb.pBt = null;
+ pDb.pSchema = null;
+ sqlite3ResetInternalSchema(db, -1);
+ return;
+
+ detach_error:
+ sqlite3_result_error(context, zErr.ToString(), -1);
+ }
-detach_error:
- sqlite3_result_error( context, zErr.ToString(), -1 );
-}
-
-/*
-** This procedure generates VDBE code for a single invocation of either the
-** sqlite_detach() or sqlite_attach() SQL user functions.
-*/
-static void codeAttach(
-Parse pParse, /* The parser context */
-int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
-FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
-Expr pAuthArg, /* Expression to pass to authorization callback */
-Expr pFilename, /* Name of database file */
-Expr pDbname, /* Name of the database to use internally */
-Expr pKey /* Database key for encryption extension */
-)
-{
- NameContext sName;
- Vdbe v;
- sqlite3 db = pParse.db;
- int regArgs;
-
- sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
- sName.pParse = pParse;
-
- if (
- SQLITE_OK != resolveAttachExpr( sName, pFilename ) ||
- SQLITE_OK != resolveAttachExpr( sName, pDbname ) ||
- SQLITE_OK != resolveAttachExpr( sName, pKey )
- )
- {
- pParse.nErr++;
- goto attach_end;
- }
+ /*
+ ** This procedure generates VDBE code for a single invocation of either the
+ ** sqlite_detach() or sqlite_attach() SQL user functions.
+ */
+ static void codeAttach(
+ Parse pParse, /* The parser context */
+ int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
+ FuncDef pFunc, /* FuncDef wrapper for detachFunc() or attachFunc() */
+ Expr pAuthArg, /* Expression to pass to authorization callback */
+ Expr pFilename, /* Name of database file */
+ Expr pDbname, /* Name of the database to use internally */
+ Expr pKey /* Database key for encryption extension */
+ ) {
+ NameContext sName;
+ Vdbe v;
+ sqlite3 db = pParse.db;
+ int regArgs;
+
+ sName = new NameContext();// memset( &sName, 0, sizeof(NameContext));
+ sName.pParse = pParse;
+
+ if (
+ SQLITE_OK != resolveAttachExpr(sName, pFilename) ||
+ SQLITE_OK != resolveAttachExpr(sName, pDbname) ||
+ SQLITE_OK != resolveAttachExpr(sName, pKey)
+ ) {
+ pParse.nErr++;
+ goto attach_end;
+ }
#if !SQLITE_OMIT_AUTHORIZATION
if( pAuthArg ){
@@ -408,258 +374,230 @@ static void codeAttach(
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
- v = sqlite3GetVdbe( pParse );
- regArgs = sqlite3GetTempRange( pParse, 4 );
- sqlite3ExprCode( pParse, pFilename, regArgs );
- sqlite3ExprCode( pParse, pDbname, regArgs + 1 );
- sqlite3ExprCode( pParse, pKey, regArgs + 2 );
-
- Debug.Assert( v != null /*|| db.mallocFailed != 0 */ );
- if ( v != null )
- {
- sqlite3VdbeAddOp3( v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3 );
- Debug.Assert( pFunc.nArg == -1 || ( pFunc.nArg & 0xff ) == pFunc.nArg );
- sqlite3VdbeChangeP5( v, (u8)( pFunc.nArg ) );
- sqlite3VdbeChangeP4( v, -1, pFunc, P4_FUNCDEF );
-
- /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
- ** statement only). For DETACH, set it to false (expire all existing
- ** statements).
- */
- sqlite3VdbeAddOp1( v, OP_Expire, ( type == SQLITE_ATTACH ) ? 1 : 0 );
- }
-
-attach_end:
- sqlite3ExprDelete( db, ref pFilename );
- sqlite3ExprDelete( db, ref pDbname );
- sqlite3ExprDelete( db, ref pKey );
-}
+ v = sqlite3GetVdbe(pParse);
+ regArgs = sqlite3GetTempRange(pParse, 4);
+ sqlite3ExprCode(pParse, pFilename, regArgs);
+ sqlite3ExprCode(pParse, pDbname, regArgs + 1);
+ sqlite3ExprCode(pParse, pKey, regArgs + 2);
+
+ Debug.Assert(v != null /*|| db.mallocFailed != 0 */ );
+ if (v != null) {
+ sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs + 3 - pFunc.nArg, regArgs + 3);
+ Debug.Assert(pFunc.nArg == -1 || (pFunc.nArg & 0xff) == pFunc.nArg);
+ sqlite3VdbeChangeP5(v, (u8)(pFunc.nArg));
+ sqlite3VdbeChangeP4(v, -1, pFunc, P4_FUNCDEF);
+
+ /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
+ ** statement only). For DETACH, set it to false (expire all existing
+ ** statements).
+ */
+ sqlite3VdbeAddOp1(v, OP_Expire, (type == SQLITE_ATTACH) ? 1 : 0);
+ }
+
+ attach_end:
+ sqlite3ExprDelete(db, ref pFilename);
+ sqlite3ExprDelete(db, ref pDbname);
+ sqlite3ExprDelete(db, ref pKey);
+ }
-/*
-** Called by the parser to compile a DETACH statement.
-**
-** DETACH pDbname
-*/
-static FuncDef detach_func = new FuncDef(
-1, /* nArg */
-SQLITE_UTF8, /* iPrefEnc */
-0, /* flags */
-null, /* pUserData */
-null, /* pNext */
-detachFunc, /* xFunc */
-null, /* xStep */
-null, /* xFinalize */
-"sqlite_detach", /* zName */
-null, /* pHash */
-null /* pDestructor */
-);
-static void sqlite3Detach( Parse pParse, Expr pDbname )
-{
- codeAttach( pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname );
-}
+ /*
+ ** Called by the parser to compile a DETACH statement.
+ **
+ ** DETACH pDbname
+ */
+ static FuncDef detach_func = new FuncDef(
+ 1, /* nArg */
+ SQLITE_UTF8, /* iPrefEnc */
+ 0, /* flags */
+ null, /* pUserData */
+ null, /* pNext */
+ detachFunc, /* xFunc */
+ null, /* xStep */
+ null, /* xFinalize */
+ "sqlite_detach", /* zName */
+ null, /* pHash */
+ null /* pDestructor */
+ );
+ static void sqlite3Detach(Parse pParse, Expr pDbname) {
+ codeAttach(pParse, SQLITE_DETACH, detach_func, pDbname, null, null, pDbname);
+ }
-/*
-** Called by the parser to compile an ATTACH statement.
-**
-** ATTACH p AS pDbname KEY pKey
-*/
-static FuncDef attach_func = new FuncDef(
-3, /* nArg */
-SQLITE_UTF8, /* iPrefEnc */
-0, /* flags */
-null, /* pUserData */
-null, /* pNext */
-attachFunc, /* xFunc */
-null, /* xStep */
-null, /* xFinalize */
-"sqlite_attach", /* zName */
-null, /* pHash */
-null /* pDestructor */
-);
-static void sqlite3Attach( Parse pParse, Expr p, Expr pDbname, Expr pKey )
-{
- codeAttach( pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey );
-}
+ /*
+ ** Called by the parser to compile an ATTACH statement.
+ **
+ ** ATTACH p AS pDbname KEY pKey
+ */
+ static FuncDef attach_func = new FuncDef(
+ 3, /* nArg */
+ SQLITE_UTF8, /* iPrefEnc */
+ 0, /* flags */
+ null, /* pUserData */
+ null, /* pNext */
+ attachFunc, /* xFunc */
+ null, /* xStep */
+ null, /* xFinalize */
+ "sqlite_attach", /* zName */
+ null, /* pHash */
+ null /* pDestructor */
+ );
+ static void sqlite3Attach(Parse pParse, Expr p, Expr pDbname, Expr pKey) {
+ codeAttach(pParse, SQLITE_ATTACH, attach_func, p, p, pDbname, pKey);
+ }
#endif // * SQLITE_OMIT_ATTACH */
-/*
-** Initialize a DbFixer structure. This routine must be called prior
-** to passing the structure to one of the sqliteFixAAAA() routines below.
-**
-** The return value indicates whether or not fixation is required. TRUE
-** means we do need to fix the database references, FALSE means we do not.
-*/
-static int sqlite3FixInit(
-DbFixer pFix, /* The fixer to be initialized */
-Parse pParse, /* Error messages will be written here */
-int iDb, /* This is the database that must be used */
-string zType, /* "view", "trigger", or "index" */
-Token pName /* Name of the view, trigger, or index */
-)
-{
- sqlite3 db;
-
- if ( NEVER( iDb < 0 ) || iDb == 1 )
- return 0;
- db = pParse.db;
- Debug.Assert( db.nDb > iDb );
- pFix.pParse = pParse;
- pFix.zDb = db.aDb[iDb].zName;
- pFix.zType = zType;
- pFix.pName = pName;
- return 1;
-}
+ /*
+ ** Initialize a DbFixer structure. This routine must be called prior
+ ** to passing the structure to one of the sqliteFixAAAA() routines below.
+ **
+ ** The return value indicates whether or not fixation is required. TRUE
+ ** means we do need to fix the database references, FALSE means we do not.
+ */
+ static int sqlite3FixInit(
+ DbFixer pFix, /* The fixer to be initialized */
+ Parse pParse, /* Error messages will be written here */
+ int iDb, /* This is the database that must be used */
+ string zType, /* "view", "trigger", or "index" */
+ Token pName /* Name of the view, trigger, or index */
+ ) {
+ sqlite3 db;
+
+ if (NEVER(iDb < 0) || iDb == 1)
+ return 0;
+ db = pParse.db;
+ Debug.Assert(db.nDb > iDb);
+ pFix.pParse = pParse;
+ pFix.zDb = db.aDb[iDb].zName;
+ pFix.zType = zType;
+ pFix.pName = pName;
+ return 1;
+ }
-/*
-** The following set of routines walk through the parse tree and assign
-** a specific database to all table references where the database name
-** was left unspecified in the original SQL statement. The pFix structure
-** must have been initialized by a prior call to sqlite3FixInit().
-**
-** These routines are used to make sure that an index, trigger, or
-** view in one database does not refer to objects in a different database.
-** (Exception: indices, triggers, and views in the TEMP database are
-** allowed to refer to anything.) If a reference is explicitly made
-** to an object in a different database, an error message is added to
-** pParse.zErrMsg and these routines return non-zero. If everything
-** checks out, these routines return 0.
-*/
-static int sqlite3FixSrcList(
-DbFixer pFix, /* Context of the fixation */
-SrcList pList /* The Source list to check and modify */
-)
-{
- int i;
- string zDb;
- SrcList_item pItem;
-
- if ( NEVER( pList == null ) )
- return 0;
- zDb = pFix.zDb;
- for ( i = 0; i < pList.nSrc; i++ )
- {//, pItem++){
- pItem = pList.a[i];
- if ( pItem.zDatabase == null )
- {
- pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
- }
- else if ( !pItem.zDatabase.Equals( zDb ,StringComparison.OrdinalIgnoreCase ) )
- {
- sqlite3ErrorMsg( pFix.pParse,
- "%s %T cannot reference objects in database %s",
- pFix.zType, pFix.pName, pItem.zDatabase );
- return 1;
- }
+ /*
+ ** The following set of routines walk through the parse tree and assign
+ ** a specific database to all table references where the database name
+ ** was left unspecified in the original SQL statement. The pFix structure
+ ** must have been initialized by a prior call to sqlite3FixInit().
+ **
+ ** These routines are used to make sure that an index, trigger, or
+ ** view in one database does not refer to objects in a different database.
+ ** (Exception: indices, triggers, and views in the TEMP database are
+ ** allowed to refer to anything.) If a reference is explicitly made
+ ** to an object in a different database, an error message is added to
+ ** pParse.zErrMsg and these routines return non-zero. If everything
+ ** checks out, these routines return 0.
+ */
+ static int sqlite3FixSrcList(
+ DbFixer pFix, /* Context of the fixation */
+ SrcList pList /* The Source list to check and modify */
+ ) {
+ int i;
+ string zDb;
+ SrcList_item pItem;
+
+ if (NEVER(pList == null))
+ return 0;
+ zDb = pFix.zDb;
+ for (i = 0; i < pList.nSrc; i++) {//, pItem++){
+ pItem = pList.a[i];
+ if (pItem.zDatabase == null) {
+ pItem.zDatabase = zDb;// sqlite3DbStrDup( pFix.pParse.db, zDb );
+ } else if (!pItem.zDatabase.Equals(zDb, StringComparison.OrdinalIgnoreCase)) {
+ sqlite3ErrorMsg(pFix.pParse,
+ "%s %T cannot reference objects in database %s",
+ pFix.zType, pFix.pName, pItem.zDatabase);
+ return 1;
+ }
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
- if ( sqlite3FixSelect( pFix, pItem.pSelect ) != 0 )
- return 1;
- if ( sqlite3FixExpr( pFix, pItem.pOn ) != 0 )
- return 1;
+ if (sqlite3FixSelect(pFix, pItem.pSelect) != 0)
+ return 1;
+ if (sqlite3FixExpr(pFix, pItem.pOn) != 0)
+ return 1;
#endif
- }
- return 0;
-}
+ }
+ return 0;
+ }
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER
-static int sqlite3FixSelect(
-DbFixer pFix, /* Context of the fixation */
-Select pSelect /* The SELECT statement to be fixed to one database */
-)
-{
- while ( pSelect != null )
- {
- if ( sqlite3FixExprList( pFix, pSelect.pEList ) != 0 )
- {
- return 1;
- }
- if ( sqlite3FixSrcList( pFix, pSelect.pSrc ) != 0 )
- {
- return 1;
- }
- if ( sqlite3FixExpr( pFix, pSelect.pWhere ) != 0 )
- {
- return 1;
- }
- if ( sqlite3FixExpr( pFix, pSelect.pHaving ) != 0 )
- {
- return 1;
- }
- pSelect = pSelect.pPrior;
- }
- return 0;
-}
-static int sqlite3FixExpr(
-DbFixer pFix, /* Context of the fixation */
-Expr pExpr /* The expression to be fixed to one database */
-)
-{
- while ( pExpr != null )
- {
- if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
- break;
- if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
- {
- if ( sqlite3FixSelect( pFix, pExpr.x.pSelect ) != 0 )
- return 1;
- }
- else
- {
- if ( sqlite3FixExprList( pFix, pExpr.x.pList ) != 0 )
- return 1;
- }
- if ( sqlite3FixExpr( pFix, pExpr.pRight ) != 0 )
- {
- return 1;
- }
- pExpr = pExpr.pLeft;
- }
- return 0;
-}
-static int sqlite3FixExprList(
-DbFixer pFix, /* Context of the fixation */
-ExprList pList /* The expression to be fixed to one database */
-)
-{
- int i;
- ExprList_item pItem;
- if ( pList == null )
- return 0;
- for ( i = 0; i < pList.nExpr; i++ )//, pItem++ )
- {
- pItem = pList.a[i];
- if ( sqlite3FixExpr( pFix, pItem.pExpr ) != 0 )
- {
- return 1;
- }
- }
- return 0;
-}
+ static int sqlite3FixSelect(
+ DbFixer pFix, /* Context of the fixation */
+ Select pSelect /* The SELECT statement to be fixed to one database */
+ ) {
+ while (pSelect != null) {
+ if (sqlite3FixExprList(pFix, pSelect.pEList) != 0) {
+ return 1;
+ }
+ if (sqlite3FixSrcList(pFix, pSelect.pSrc) != 0) {
+ return 1;
+ }
+ if (sqlite3FixExpr(pFix, pSelect.pWhere) != 0) {
+ return 1;
+ }
+ if (sqlite3FixExpr(pFix, pSelect.pHaving) != 0) {
+ return 1;
+ }
+ pSelect = pSelect.pPrior;
+ }
+ return 0;
+ }
+ static int sqlite3FixExpr(
+ DbFixer pFix, /* Context of the fixation */
+ Expr pExpr /* The expression to be fixed to one database */
+ ) {
+ while (pExpr != null) {
+ if (ExprHasAnyProperty(pExpr, EP_TokenOnly))
+ break;
+ if (ExprHasProperty(pExpr, EP_xIsSelect)) {
+ if (sqlite3FixSelect(pFix, pExpr.x.pSelect) != 0)
+ return 1;
+ } else {
+ if (sqlite3FixExprList(pFix, pExpr.x.pList) != 0)
+ return 1;
+ }
+ if (sqlite3FixExpr(pFix, pExpr.pRight) != 0) {
+ return 1;
+ }
+ pExpr = pExpr.pLeft;
+ }
+ return 0;
+ }
+ static int sqlite3FixExprList(
+ DbFixer pFix, /* Context of the fixation */
+ ExprList pList /* The expression to be fixed to one database */
+ ) {
+ int i;
+ ExprList_item pItem;
+ if (pList == null)
+ return 0;
+ for (i = 0; i < pList.nExpr; i++)//, pItem++ )
+ {
+ pItem = pList.a[i];
+ if (sqlite3FixExpr(pFix, pItem.pExpr) != 0) {
+ return 1;
+ }
+ }
+ return 0;
+ }
#endif
#if !SQLITE_OMIT_TRIGGER
-static int sqlite3FixTriggerStep(
-DbFixer pFix, /* Context of the fixation */
-TriggerStep pStep /* The trigger step be fixed to one database */
-)
-{
- while ( pStep != null )
- {
- if ( sqlite3FixSelect( pFix, pStep.pSelect ) != 0 )
- {
- return 1;
- }
- if ( sqlite3FixExpr( pFix, pStep.pWhere ) != 0 )
- {
- return 1;
- }
- if ( sqlite3FixExprList( pFix, pStep.pExprList ) != 0 )
- {
- return 1;
- }
- pStep = pStep.pNext;
- }
- return 0;
-}
+ static int sqlite3FixTriggerStep(
+ DbFixer pFix, /* Context of the fixation */
+ TriggerStep pStep /* The trigger step be fixed to one database */
+ ) {
+ while (pStep != null) {
+ if (sqlite3FixSelect(pFix, pStep.pSelect) != 0) {
+ return 1;
+ }
+ if (sqlite3FixExpr(pFix, pStep.pWhere) != 0) {
+ return 1;
+ }
+ if (sqlite3FixExprList(pFix, pStep.pExprList) != 0) {
+ return 1;
+ }
+ pStep = pStep.pNext;
+ }
+ return 0;
+ }
#endif
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/auth_c.cs b/Src/IronPython.SQLite/c#sqlite/auth_c.cs
index f2ee6a610..846777e9f 100644
--- a/Src/IronPython.SQLite/c#sqlite/auth_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/auth_c.cs
@@ -1,42 +1,34 @@
-using System;
-using System.Diagnostics;
-using System.Text;
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2003 January 11
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains code used to implement the sqlite3_set_authorizer()
+ ** API. This facility is an optional feature of the library. Embedded
+ ** systems that do not need this facility may omit it by recompiling
+ ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
-
- public partial class Sqlite3
- {
-/*
-** 2003 January 11
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains code used to implement the sqlite3_set_authorizer()
-** API. This facility is an optional feature of the library. Embedded
-** systems that do not need this facility may omit it by recompiling
-** the library with -DSQLITE_OMIT_AUTHORIZATION=1
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
-**
-*************************************************************************
-*/
-//#include "sqliteInt.h"
-
-/*
-** All of the code in this file may be omitted by defining a single
-** macro.
-*/
+ /*
+ ** All of the code in this file may be omitted by defining a single
+ ** macro.
+ */
#if !SQLITE_OMIT_AUTHORIZATION
/*
@@ -263,5 +255,5 @@ void sqlite3AuthContextPop(AuthContext *pContext){
}
#endif //* SQLITE_OMIT_AUTHORIZATION */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/backup_c.cs b/Src/IronPython.SQLite/c#sqlite/backup_c.cs
index 7936670f6..51939abd2 100644
--- a/Src/IronPython.SQLite/c#sqlite/backup_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/backup_c.cs
@@ -1,289 +1,263 @@
using System;
using System.Diagnostics;
-using System.Text;
using i64 = System.Int64;
-using u8 = System.Byte;
+using Pgno = System.UInt32;
using u32 = System.UInt32;
-using Pgno = System.UInt32;
+namespace Community.CsharpSqlite {
+ using DbPage = Sqlite3.PgHdr;
+ public partial class Sqlite3 {
+ /*
+ ** 2009 January 28
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains the implementation of the sqlite3_backup_XXX()
+ ** API functions and the related features.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
+ //#include "btreeInt.h"
-namespace Community.CsharpSqlite
-{
- using sqlite3_int64 = System.Int64;
- using DbPage = Sqlite3.PgHdr;
- public partial class Sqlite3
- {
-/*
-** 2009 January 28
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file contains the implementation of the sqlite3_backup_XXX()
-** API functions and the related features.
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
-**
-*************************************************************************
-*/
-//#include "sqliteInt.h"
-//#include "btreeInt.h"
-
-/* Macro to find the minimum of two numeric values.
-*/
+ /* Macro to find the minimum of two numeric values.
+ */
#if !MIN
-//# define MIN(x,y) ((x)<(y)?(x):(y))
+ //# define MIN(x,y) ((x)<(y)?(x):(y))
#endif
-/*
-** Structure allocated for each backup operation.
-*/
-public class sqlite3_backup
-{
- public sqlite3 pDestDb; /* Destination database handle */
- public Btree pDest; /* Destination b-tree file */
- public u32 iDestSchema; /* Original schema cookie in destination */
- public int bDestLocked; /* True once a write-transaction is open on pDest */
-
- public Pgno iNext; /* Page number of the next source page to copy */
- public sqlite3 pSrcDb; /* Source database handle */
- public Btree pSrc; /* Source b-tree file */
-
- public int rc; /* Backup process error code */
-
- /* These two variables are set by every call to backup_step(). They are
- ** read by calls to backup_remaining() and backup_pagecount().
- */
- public Pgno nRemaining; /* Number of pages left to copy */
- public Pgno nPagecount; /* Total number of pages to copy */
-
- public int isAttached; /* True once backup has been registered with pager */
- public sqlite3_backup pNext; /* Next backup associated with source pager */
-};
-
-/*
-** THREAD SAFETY NOTES:
-**
-** Once it has been created using backup_init(), a single sqlite3_backup
-** structure may be accessed via two groups of thread-safe entry points:
-**
-** * Via the sqlite3_backup_XXX() API function backup_step() and
-** backup_finish(). Both these functions obtain the source database
-** handle mutex and the mutex associated with the source BtShared
-** structure, in that order.
-**
-** * Via the BackupUpdate() and BackupRestart() functions, which are
-** invoked by the pager layer to report various state changes in
-** the page cache associated with the source database. The mutex
-** associated with the source database BtShared structure will always
-** be held when either of these functions are invoked.
-**
-** The other sqlite3_backup_XXX() API functions, backup_remaining() and
-** backup_pagecount() are not thread-safe functions. If they are called
-** while some other thread is calling backup_step() or backup_finish(),
-** the values returned may be invalid. There is no way for a call to
-** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
-** or backup_pagecount().
-**
-** Depending on the SQLite configuration, the database handles and/or
-** the Btree objects may have their own mutexes that require locking.
-** Non-sharable Btrees (in-memory databases for example), do not have
-** associated mutexes.
-*/
-
-/*
-** Return a pointer corresponding to database zDb (i.e. "main", "temp")
-** in connection handle pDb. If such a database cannot be found, return
-** a NULL pointer and write an error message to pErrorDb.
-**
-** If the "temp" database is requested, it may need to be opened by this
-** function. If an error occurs while doing so, return 0 and write an
-** error message to pErrorDb.
-*/
-static Btree findBtree( sqlite3 pErrorDb, sqlite3 pDb, string zDb )
-{
- int i = sqlite3FindDbName( pDb, zDb );
-
- if ( i == 1 )
- {
- Parse pParse;
- int rc = 0;
- pParse = new Parse();//sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
- if ( pParse == null )
- {
- sqlite3Error( pErrorDb, SQLITE_NOMEM, "out of memory" );
- rc = SQLITE_NOMEM;
- }
- else
- {
- pParse.db = pDb;
- if ( sqlite3OpenTempDatabase( pParse ) != 0 )
- {
- sqlite3Error( pErrorDb, pParse.rc, "%s", pParse.zErrMsg );
- rc = SQLITE_ERROR;
- }
- sqlite3DbFree( pErrorDb, ref pParse.zErrMsg );
- //sqlite3StackFree( pErrorDb, pParse );
- }
- if ( rc != 0 )
- {
- return null;
- }
- }
-
- if ( i < 0 )
- {
- sqlite3Error( pErrorDb, SQLITE_ERROR, "unknown database %s", zDb );
- return null;
- }
-
- return pDb.aDb[i].pBt;
-}
-
-/*
-** Attempt to set the page size of the destination to match the page size
-** of the source.
-*/
-static int setDestPgsz( sqlite3_backup p )
-{
- int rc;
- rc = sqlite3BtreeSetPageSize( p.pDest, sqlite3BtreeGetPageSize( p.pSrc ), -1, 0 );
- return rc;
-}
-
-/*
-** Create an sqlite3_backup process to copy the contents of zSrcDb from
-** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
-** a pointer to the new sqlite3_backup object.
-**
-** If an error occurs, NULL is returned and an error code and error message
-** stored in database handle pDestDb.
-*/
-static public sqlite3_backup sqlite3_backup_init(
-sqlite3 pDestDb, /* Database to write to */
-string zDestDb, /* Name of database within pDestDb */
-sqlite3 pSrcDb, /* Database connection to read from */
-string zSrcDb /* Name of database within pSrcDb */
-)
-{
- sqlite3_backup p; /* Value to return */
-
- /* Lock the source database handle. The destination database
- ** handle is not locked in this routine, but it is locked in
- ** sqlite3_backup_step(). The user is required to ensure that no
- ** other thread accesses the destination handle for the duration
- ** of the backup operation. Any attempt to use the destination
- ** database connection while a backup is in progress may cause
- ** a malfunction or a deadlock.
- */
- sqlite3_mutex_enter( pSrcDb.mutex );
- sqlite3_mutex_enter( pDestDb.mutex );
-
- if ( pSrcDb == pDestDb )
- {
- sqlite3Error(
- pDestDb, SQLITE_ERROR, "source and destination must be distinct"
- );
- p = null;
- }
- else
- {
- /* Allocate space for a new sqlite3_backup object...
- ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
- ** call to sqlite3_backup_init() and is destroyed by a call to
- ** sqlite3_backup_finish(). */
- p = new sqlite3_backup();// (sqlite3_backup)sqlite3_malloc( sizeof( sqlite3_backup ) );
- //if ( null == p )
- //{
- // sqlite3Error( pDestDb, SQLITE_NOMEM, 0 );
- //}
- }
+ /*
+ ** Structure allocated for each backup operation.
+ */
+ public class sqlite3_backup {
+ public sqlite3 pDestDb; /* Destination database handle */
+ public Btree pDest; /* Destination b-tree file */
+ public u32 iDestSchema; /* Original schema cookie in destination */
+ public int bDestLocked; /* True once a write-transaction is open on pDest */
+
+ public Pgno iNext; /* Page number of the next source page to copy */
+ public sqlite3 pSrcDb; /* Source database handle */
+ public Btree pSrc; /* Source b-tree file */
+
+ public int rc; /* Backup process error code */
+
+ /* These two variables are set by every call to backup_step(). They are
+ ** read by calls to backup_remaining() and backup_pagecount().
+ */
+ public Pgno nRemaining; /* Number of pages left to copy */
+ public Pgno nPagecount; /* Total number of pages to copy */
+
+ public int isAttached; /* True once backup has been registered with pager */
+ public sqlite3_backup pNext; /* Next backup associated with source pager */
+ };
+
+ /*
+ ** THREAD SAFETY NOTES:
+ **
+ ** Once it has been created using backup_init(), a single sqlite3_backup
+ ** structure may be accessed via two groups of thread-safe entry points:
+ **
+ ** * Via the sqlite3_backup_XXX() API function backup_step() and
+ ** backup_finish(). Both these functions obtain the source database
+ ** handle mutex and the mutex associated with the source BtShared
+ ** structure, in that order.
+ **
+ ** * Via the BackupUpdate() and BackupRestart() functions, which are
+ ** invoked by the pager layer to report various state changes in
+ ** the page cache associated with the source database. The mutex
+ ** associated with the source database BtShared structure will always
+ ** be held when either of these functions are invoked.
+ **
+ ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
+ ** backup_pagecount() are not thread-safe functions. If they are called
+ ** while some other thread is calling backup_step() or backup_finish(),
+ ** the values returned may be invalid. There is no way for a call to
+ ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
+ ** or backup_pagecount().
+ **
+ ** Depending on the SQLite configuration, the database handles and/or
+ ** the Btree objects may have their own mutexes that require locking.
+ ** Non-sharable Btrees (in-memory databases for example), do not have
+ ** associated mutexes.
+ */
- /* If the allocation succeeded, populate the new object. */
- if ( p != null )
- {
- // memset( p, 0, sizeof( sqlite3_backup ) );
- p.pSrc = findBtree( pDestDb, pSrcDb, zSrcDb );
- p.pDest = findBtree( pDestDb, pDestDb, zDestDb );
- p.pDestDb = pDestDb;
- p.pSrcDb = pSrcDb;
- p.iNext = 1;
- p.isAttached = 0;
-
- if ( null == p.pSrc || null == p.pDest || setDestPgsz( p ) == SQLITE_NOMEM )
- {
- /* One (or both) of the named databases did not exist or an OOM
- ** error was hit. The error has already been written into the
- ** pDestDb handle. All that is left to do here is free the
- ** sqlite3_backup structure.
- */
- //sqlite3_free( ref p );
- p = null;
- }
- }
+ /*
+ ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
+ ** in connection handle pDb. If such a database cannot be found, return
+ ** a NULL pointer and write an error message to pErrorDb.
+ **
+ ** If the "temp" database is requested, it may need to be opened by this
+ ** function. If an error occurs while doing so, return 0 and write an
+ ** error message to pErrorDb.
+ */
+ static Btree findBtree(sqlite3 pErrorDb, sqlite3 pDb, string zDb) {
+ int i = sqlite3FindDbName(pDb, zDb);
+
+ if (i == 1) {
+ Parse pParse;
+ int rc = 0;
+ pParse = new Parse();//sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
+ if (pParse == null) {
+ sqlite3Error(pErrorDb, SQLITE_NOMEM, "out of memory");
+ rc = SQLITE_NOMEM;
+ } else {
+ pParse.db = pDb;
+ if (sqlite3OpenTempDatabase(pParse) != 0) {
+ sqlite3Error(pErrorDb, pParse.rc, "%s", pParse.zErrMsg);
+ rc = SQLITE_ERROR;
+ }
+ sqlite3DbFree(pErrorDb, ref pParse.zErrMsg);
+ //sqlite3StackFree( pErrorDb, pParse );
+ }
+ if (rc != 0) {
+ return null;
+ }
+ }
+
+ if (i < 0) {
+ sqlite3Error(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
+ return null;
+ }
+
+ return pDb.aDb[i].pBt;
+ }
- if ( p != null )
- {
- p.pSrc.nBackup++;
- }
+ /*
+ ** Attempt to set the page size of the destination to match the page size
+ ** of the source.
+ */
+ static int setDestPgsz(sqlite3_backup p) {
+ int rc;
+ rc = sqlite3BtreeSetPageSize(p.pDest, sqlite3BtreeGetPageSize(p.pSrc), -1, 0);
+ return rc;
+ }
- sqlite3_mutex_leave( pDestDb.mutex );
- sqlite3_mutex_leave( pSrcDb.mutex );
- return p;
-}
+ /*
+ ** Create an sqlite3_backup process to copy the contents of zSrcDb from
+ ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
+ ** a pointer to the new sqlite3_backup object.
+ **
+ ** If an error occurs, NULL is returned and an error code and error message
+ ** stored in database handle pDestDb.
+ */
+ static public sqlite3_backup sqlite3_backup_init(
+ sqlite3 pDestDb, /* Database to write to */
+ string zDestDb, /* Name of database within pDestDb */
+ sqlite3 pSrcDb, /* Database connection to read from */
+ string zSrcDb /* Name of database within pSrcDb */
+ ) {
+ sqlite3_backup p; /* Value to return */
+
+ /* Lock the source database handle. The destination database
+ ** handle is not locked in this routine, but it is locked in
+ ** sqlite3_backup_step(). The user is required to ensure that no
+ ** other thread accesses the destination handle for the duration
+ ** of the backup operation. Any attempt to use the destination
+ ** database connection while a backup is in progress may cause
+ ** a malfunction or a deadlock.
+ */
+ sqlite3_mutex_enter(pSrcDb.mutex);
+ sqlite3_mutex_enter(pDestDb.mutex);
+
+ if (pSrcDb == pDestDb) {
+ sqlite3Error(
+ pDestDb, SQLITE_ERROR, "source and destination must be distinct"
+ );
+ p = null;
+ } else {
+ /* Allocate space for a new sqlite3_backup object...
+ ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
+ ** call to sqlite3_backup_init() and is destroyed by a call to
+ ** sqlite3_backup_finish(). */
+ p = new sqlite3_backup();// (sqlite3_backup)sqlite3_malloc( sizeof( sqlite3_backup ) );
+ //if ( null == p )
+ //{
+ // sqlite3Error( pDestDb, SQLITE_NOMEM, 0 );
+ //}
+ }
+
+ /* If the allocation succeeded, populate the new object. */
+ if (p != null) {
+ // memset( p, 0, sizeof( sqlite3_backup ) );
+ p.pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
+ p.pDest = findBtree(pDestDb, pDestDb, zDestDb);
+ p.pDestDb = pDestDb;
+ p.pSrcDb = pSrcDb;
+ p.iNext = 1;
+ p.isAttached = 0;
+
+ if (null == p.pSrc || null == p.pDest || setDestPgsz(p) == SQLITE_NOMEM) {
+ /* One (or both) of the named databases did not exist or an OOM
+ ** error was hit. The error has already been written into the
+ ** pDestDb handle. All that is left to do here is free the
+ ** sqlite3_backup structure.
+ */
+ //sqlite3_free( ref p );
+ p = null;
+ }
+ }
+
+ if (p != null) {
+ p.pSrc.nBackup++;
+ }
+
+ sqlite3_mutex_leave(pDestDb.mutex);
+ sqlite3_mutex_leave(pSrcDb.mutex);
+ return p;
+ }
-/*
-** Argument rc is an SQLite error code. Return true if this error is
-** considered fatal if encountered during a backup operation. All errors
-** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
-*/
-static bool isFatalError( int rc )
-{
- return ( rc != SQLITE_OK && rc != SQLITE_BUSY && ALWAYS( rc != SQLITE_LOCKED ) );
-}
+ /*
+ ** Argument rc is an SQLite error code. Return true if this error is
+ ** considered fatal if encountered during a backup operation. All errors
+ ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
+ */
+ static bool isFatalError(int rc) {
+ return (rc != SQLITE_OK && rc != SQLITE_BUSY && ALWAYS(rc != SQLITE_LOCKED));
+ }
-/*
-** Parameter zSrcData points to a buffer containing the data for
-** page iSrcPg from the source database. Copy this data into the
-** destination database.
-*/
-static int backupOnePage( sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData )
-{
- Pager pDestPager = sqlite3BtreePager( p.pDest );
- int nSrcPgsz = sqlite3BtreeGetPageSize( p.pSrc );
- int nDestPgsz = sqlite3BtreeGetPageSize( p.pDest );
- int nCopy = MIN( nSrcPgsz, nDestPgsz );
- i64 iEnd = (i64)iSrcPg * (i64)nSrcPgsz;
+ /*
+ ** Parameter zSrcData points to a buffer containing the data for
+ ** page iSrcPg from the source database. Copy this data into the
+ ** destination database.
+ */
+ static int backupOnePage(sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData) {
+ Pager pDestPager = sqlite3BtreePager(p.pDest);
+ int nSrcPgsz = sqlite3BtreeGetPageSize(p.pSrc);
+ int nDestPgsz = sqlite3BtreeGetPageSize(p.pDest);
+ int nCopy = MIN(nSrcPgsz, nDestPgsz);
+ i64 iEnd = (i64)iSrcPg * (i64)nSrcPgsz;
#if SQLITE_HAS_CODEC
int nSrcReserve = sqlite3BtreeGetReserve(p.pSrc);
int nDestReserve = sqlite3BtreeGetReserve(p.pDest);
#endif
- int rc = SQLITE_OK;
- i64 iOff;
+ int rc = SQLITE_OK;
+ i64 iOff;
- Debug.Assert( p.bDestLocked != 0 );
- Debug.Assert( !isFatalError( p.rc ) );
- Debug.Assert( iSrcPg != PENDING_BYTE_PAGE( p.pSrc.pBt ) );
- Debug.Assert( zSrcData != null );
+ Debug.Assert(p.bDestLocked != 0);
+ Debug.Assert(!isFatalError(p.rc));
+ Debug.Assert(iSrcPg != PENDING_BYTE_PAGE(p.pSrc.pBt));
+ Debug.Assert(zSrcData != null);
- /* Catch the case where the destination is an in-memory database and the
- ** page sizes of the source and destination differ.
- */
- if ( nSrcPgsz != nDestPgsz && sqlite3PagerIsMemdb( pDestPager ) )
- {
- rc = SQLITE_READONLY;
- }
+ /* Catch the case where the destination is an in-memory database and the
+ ** page sizes of the source and destination differ.
+ */
+ if (nSrcPgsz != nDestPgsz && sqlite3PagerIsMemdb(pDestPager)) {
+ rc = SQLITE_READONLY;
+ }
#if SQLITE_HAS_CODEC
/* Backup is not possible if the page size of the destination is changing
@@ -308,511 +282,456 @@ static int backupOnePage( sqlite3_backup p, Pgno iSrcPg, byte[] zSrcData )
}
#endif
- /* This loop runs once for each destination page spanned by the source
- ** page. For each iteration, variable iOff is set to the byte offset
- ** of the destination page.
- */
- for ( iOff = iEnd - (i64)nSrcPgsz; rc == SQLITE_OK && iOff < iEnd; iOff += nDestPgsz )
- {
- DbPage pDestPg = null;
- u32 iDest = (u32)( iOff / nDestPgsz ) + 1;
- if ( iDest == PENDING_BYTE_PAGE( p.pDest.pBt ) )
- continue;
- if ( SQLITE_OK == ( rc = sqlite3PagerGet( pDestPager, iDest, ref pDestPg ) )
- && SQLITE_OK == ( rc = sqlite3PagerWrite( pDestPg ) )
- )
- {
- //string zIn = &zSrcData[iOff%nSrcPgsz];
- byte[] zDestData = sqlite3PagerGetData( pDestPg );
- //string zOut = &zDestData[iOff % nDestPgsz];
-
- /* Copy the data from the source page into the destination page.
- ** Then clear the Btree layer MemPage.isInit flag. Both this module
- ** and the pager code use this trick (clearing the first byte
- ** of the page 'extra' space to invalidate the Btree layers
- ** cached parse of the page). MemPage.isInit is marked
- ** "MUST BE FIRST" for this purpose.
- */
- Buffer.BlockCopy( zSrcData, (int)( iOff % nSrcPgsz ), zDestData, (int)( iOff % nDestPgsz ), nCopy );// memcpy( zOut, zIn, nCopy );
- sqlite3PagerGetExtra( pDestPg ).isInit = 0;// ( sqlite3PagerGetExtra( pDestPg ) )[0] = 0;
- }
- sqlite3PagerUnref( pDestPg );
- }
-
- return rc;
-}
-
-/*
-** If pFile is currently larger than iSize bytes, then truncate it to
-** exactly iSize bytes. If pFile is not larger than iSize bytes, then
-** this function is a no-op.
-**
-** Return SQLITE_OK if everything is successful, or an SQLite error
-** code if an error occurs.
-*/
-static int backupTruncateFile( sqlite3_file pFile, int iSize )
-{
- long iCurrent = 0;
- int rc = sqlite3OsFileSize( pFile, ref iCurrent );
- if ( rc == SQLITE_OK && iCurrent > iSize )
- {
- rc = sqlite3OsTruncate( pFile, iSize );
- }
- return rc;
-}
-
-/*
-** Register this backup object with the associated source pager for
-** callbacks when pages are changed or the cache invalidated.
-*/
-static void attachBackupObject( sqlite3_backup p )
-{
- sqlite3_backup pp;
- Debug.Assert( sqlite3BtreeHoldsMutex( p.pSrc ) );
- pp = sqlite3PagerBackupPtr( sqlite3BtreePager( p.pSrc ) );
- p.pNext = pp;
- sqlite3BtreePager( p.pSrc ).pBackup = p; //*pp = p;
- p.isAttached = 1;
-}
-
-/*
-** Copy nPage pages from the source b-tree to the destination.
-*/
-static public int sqlite3_backup_step( sqlite3_backup p, int nPage )
-{
- int rc;
- int destMode; /* Destination journal mode */
- int pgszSrc = 0; /* Source page size */
- int pgszDest = 0; /* Destination page size */
-
- sqlite3_mutex_enter( p.pSrcDb.mutex );
- sqlite3BtreeEnter( p.pSrc );
- if ( p.pDestDb != null )
- {
- sqlite3_mutex_enter( p.pDestDb.mutex );
- }
-
- rc = p.rc;
- if ( !isFatalError( rc ) )
- {
- Pager pSrcPager = sqlite3BtreePager( p.pSrc ); /* Source pager */
- Pager pDestPager = sqlite3BtreePager( p.pDest ); /* Dest pager */
- int ii; /* Iterator variable */
- Pgno nSrcPage = 0; /* Size of source db in pages */
- int bCloseTrans = 0; /* True if src db requires unlocking */
-
- /* If the source pager is currently in a write-transaction, return
- ** SQLITE_BUSY immediately.
- */
- if ( p.pDestDb != null && p.pSrc.pBt.inTransaction == TRANS_WRITE )
- {
- rc = SQLITE_BUSY;
- }
- else
- {
- rc = SQLITE_OK;
- }
-
- /* Lock the destination database, if it is not locked already. */
- if ( SQLITE_OK == rc && p.bDestLocked == 0
- && SQLITE_OK == ( rc = sqlite3BtreeBeginTrans( p.pDest, 2 ) )
- )
- {
- p.bDestLocked = 1;
- sqlite3BtreeGetMeta( p.pDest, BTREE_SCHEMA_VERSION, ref p.iDestSchema );
- }
-
- /* If there is no open read-transaction on the source database, open
- ** one now. If a transaction is opened here, then it will be closed
- ** before this function exits.
- */
- if ( rc == SQLITE_OK && !sqlite3BtreeIsInReadTrans( p.pSrc ) )
- {
- rc = sqlite3BtreeBeginTrans( p.pSrc, 0 );
- bCloseTrans = 1;
- }
-
- /* Do not allow backup if the destination database is in WAL mode
- ** and the page sizes are different between source and destination */
- pgszSrc = sqlite3BtreeGetPageSize( p.pSrc );
- pgszDest = sqlite3BtreeGetPageSize( p.pDest );
- destMode = sqlite3PagerGetJournalMode( sqlite3BtreePager( p.pDest ) );
- if ( SQLITE_OK == rc && destMode == PAGER_JOURNALMODE_WAL && pgszSrc != pgszDest )
- {
- rc = SQLITE_READONLY;
- }
-
- /* Now that there is a read-lock on the source database, query the
- ** source pager for the number of pages in the database.
- */
- nSrcPage = sqlite3BtreeLastPage( p.pSrc );
- Debug.Assert( nSrcPage >= 0 );
-
- for ( ii = 0; ( nPage < 0 || ii < nPage ) && p.iNext <= nSrcPage && 0 == rc; ii++ )
- {
- Pgno iSrcPg = p.iNext; /* Source page number */
- if ( iSrcPg != PENDING_BYTE_PAGE( p.pSrc.pBt ) )
- {
- DbPage pSrcPg = null; /* Source page object */
- rc = sqlite3PagerGet( pSrcPager, (u32)iSrcPg, ref pSrcPg );
- if ( rc == SQLITE_OK )
- {
- rc = backupOnePage( p, iSrcPg, sqlite3PagerGetData( pSrcPg ) );
- sqlite3PagerUnref( pSrcPg );
+ /* This loop runs once for each destination page spanned by the source
+ ** page. For each iteration, variable iOff is set to the byte offset
+ ** of the destination page.
+ */
+ for (iOff = iEnd - (i64)nSrcPgsz; rc == SQLITE_OK && iOff < iEnd; iOff += nDestPgsz) {
+ DbPage pDestPg = null;
+ u32 iDest = (u32)(iOff / nDestPgsz) + 1;
+ if (iDest == PENDING_BYTE_PAGE(p.pDest.pBt))
+ continue;
+ if (SQLITE_OK == (rc = sqlite3PagerGet(pDestPager, iDest, ref pDestPg))
+ && SQLITE_OK == (rc = sqlite3PagerWrite(pDestPg))
+ ) {
+ //string zIn = &zSrcData[iOff%nSrcPgsz];
+ byte[] zDestData = sqlite3PagerGetData(pDestPg);
+ //string zOut = &zDestData[iOff % nDestPgsz];
+
+ /* Copy the data from the source page into the destination page.
+ ** Then clear the Btree layer MemPage.isInit flag. Both this module
+ ** and the pager code use this trick (clearing the first byte
+ ** of the page 'extra' space to invalidate the Btree layers
+ ** cached parse of the page). MemPage.isInit is marked
+ ** "MUST BE FIRST" for this purpose.
+ */
+ Buffer.BlockCopy(zSrcData, (int)(iOff % nSrcPgsz), zDestData, (int)(iOff % nDestPgsz), nCopy);// memcpy( zOut, zIn, nCopy );
+ sqlite3PagerGetExtra(pDestPg).isInit = 0;// ( sqlite3PagerGetExtra( pDestPg ) )[0] = 0;
+ }
+ sqlite3PagerUnref(pDestPg);
+ }
+
+ return rc;
}
- }
- p.iNext++;
- }
- if ( rc == SQLITE_OK )
- {
- p.nPagecount = nSrcPage;
- p.nRemaining = ( nSrcPage + 1 - p.iNext );
- if ( p.iNext > nSrcPage )
- {
- rc = SQLITE_DONE;
- }
- else if ( 0 == p.isAttached )
- {
- attachBackupObject( p );
- }
- }
-
- /* Update the schema version field in the destination database. This
- ** is to make sure that the schema-version really does change in
- ** the case where the source and destination databases have the
- ** same schema version.
- */
- if ( rc == SQLITE_DONE
- && ( rc = sqlite3BtreeUpdateMeta( p.pDest, 1, p.iDestSchema + 1 ) ) == SQLITE_OK
- )
- {
- Pgno nDestTruncate;
- if ( p.pDestDb != null )
- {
- sqlite3ResetInternalSchema( p.pDestDb, -1 );
- }
-
- /* Set nDestTruncate to the final number of pages in the destination
- ** database. The complication here is that the destination page
- ** size may be different to the source page size.
- **
- ** If the source page size is smaller than the destination page size,
- ** round up. In this case the call to sqlite3OsTruncate() below will
- ** fix the size of the file. However it is important to call
- ** sqlite3PagerTruncateImage() here so that any pages in the
- ** destination file that lie beyond the nDestTruncate page mark are
- ** journalled by PagerCommitPhaseOne() before they are destroyed
- ** by the file truncation.
- */
- Debug.Assert( pgszSrc == sqlite3BtreeGetPageSize( p.pSrc ) );
- Debug.Assert( pgszDest == sqlite3BtreeGetPageSize( p.pDest ) );
- if ( pgszSrc < pgszDest )
- {
- int ratio = pgszDest / pgszSrc;
- nDestTruncate = (Pgno)( ( nSrcPage + ratio - 1 ) / ratio );
- if ( nDestTruncate == (int)PENDING_BYTE_PAGE( p.pDest.pBt ) )
- {
- nDestTruncate--;
- }
- }
- else
- {
- nDestTruncate = (Pgno)( nSrcPage * ( pgszSrc / pgszDest ) );
- }
- sqlite3PagerTruncateImage( pDestPager, nDestTruncate );
-
- if ( pgszSrc < pgszDest )
- {
- /* If the source page-size is smaller than the destination page-size,
- ** two extra things may need to happen:
- **
- ** * The destination may need to be truncated, and
+ /*
+ ** If pFile is currently larger than iSize bytes, then truncate it to
+ ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
+ ** this function is a no-op.
**
- ** * Data stored on the pages immediately following the
- ** pending-byte page in the source database may need to be
- ** copied into the destination database.
+ ** Return SQLITE_OK if everything is successful, or an SQLite error
+ ** code if an error occurs.
*/
- int iSize = (int)( pgszSrc * nSrcPage );
- sqlite3_file pFile = sqlite3PagerFile( pDestPager );
- i64 iOff;
- i64 iEnd;
-
- Debug.Assert( pFile != null );
- Debug.Assert( (i64)nDestTruncate * (i64)pgszDest >= iSize || (
- nDestTruncate == (int)( PENDING_BYTE_PAGE( p.pDest.pBt ) - 1 )
- && iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + pgszDest
- ) );
-
- /* This call ensures that all data required to recreate the original
- ** database has been stored in the journal for pDestPager and the
- ** journal synced to disk. So at this point we may safely modify
- ** the database file in any way, knowing that if a power failure
- ** occurs, the original database will be reconstructed from the
- ** journal file. */
- rc = sqlite3PagerCommitPhaseOne( pDestPager, null, true );
-
- /* Write the extra pages and truncate the database file as required. */
- iEnd = MIN( PENDING_BYTE + pgszDest, iSize );
- for (
- iOff = PENDING_BYTE + pgszSrc;
- rc == SQLITE_OK && iOff < iEnd;
- iOff += pgszSrc
- )
- {
- PgHdr pSrcPg = null;
- u32 iSrcPg = (u32)( ( iOff / pgszSrc ) + 1 );
- rc = sqlite3PagerGet( pSrcPager, iSrcPg, ref pSrcPg );
- if ( rc == SQLITE_OK )
- {
- byte[] zData = sqlite3PagerGetData( pSrcPg );
- rc = sqlite3OsWrite( pFile, zData, pgszSrc, iOff );
- }
- sqlite3PagerUnref( pSrcPg );
- }
- if ( rc == SQLITE_OK )
- {
- rc = backupTruncateFile( pFile, (int)iSize );
+ static int backupTruncateFile(sqlite3_file pFile, int iSize) {
+ long iCurrent = 0;
+ int rc = sqlite3OsFileSize(pFile, ref iCurrent);
+ if (rc == SQLITE_OK && iCurrent > iSize) {
+ rc = sqlite3OsTruncate(pFile, iSize);
+ }
+ return rc;
}
- /* Sync the database file to disk. */
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3PagerSync( pDestPager );
+ /*
+ ** Register this backup object with the associated source pager for
+ ** callbacks when pages are changed or the cache invalidated.
+ */
+ static void attachBackupObject(sqlite3_backup p) {
+ sqlite3_backup pp;
+ Debug.Assert(sqlite3BtreeHoldsMutex(p.pSrc));
+ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p.pSrc));
+ p.pNext = pp;
+ sqlite3BtreePager(p.pSrc).pBackup = p; //*pp = p;
+ p.isAttached = 1;
}
- }
- else
- {
- rc = sqlite3PagerCommitPhaseOne( pDestPager, null, false );
- }
-
- /* Finish committing the transaction to the destination database. */
- if ( SQLITE_OK == rc
- && SQLITE_OK == ( rc = sqlite3BtreeCommitPhaseTwo( p.pDest, 0 ) )
- )
- {
- rc = SQLITE_DONE;
- }
- }
- /* If bCloseTrans is true, then this function opened a read transaction
- ** on the source database. Close the read transaction here. There is
- ** no need to check the return values of the btree methods here, as
- ** "committing" a read-only transaction cannot fail.
- */
- if ( bCloseTrans != 0 )
- {
+ /*
+ ** Copy nPage pages from the source b-tree to the destination.
+ */
+ static public int sqlite3_backup_step(sqlite3_backup p, int nPage) {
+ int rc;
+ int destMode; /* Destination journal mode */
+ int pgszSrc = 0; /* Source page size */
+ int pgszDest = 0; /* Destination page size */
+
+ sqlite3_mutex_enter(p.pSrcDb.mutex);
+ sqlite3BtreeEnter(p.pSrc);
+ if (p.pDestDb != null) {
+ sqlite3_mutex_enter(p.pDestDb.mutex);
+ }
+
+ rc = p.rc;
+ if (!isFatalError(rc)) {
+ Pager pSrcPager = sqlite3BtreePager(p.pSrc); /* Source pager */
+ Pager pDestPager = sqlite3BtreePager(p.pDest); /* Dest pager */
+ int ii; /* Iterator variable */
+ Pgno nSrcPage = 0; /* Size of source db in pages */
+ int bCloseTrans = 0; /* True if src db requires unlocking */
+
+ /* If the source pager is currently in a write-transaction, return
+ ** SQLITE_BUSY immediately.
+ */
+ if (p.pDestDb != null && p.pSrc.pBt.inTransaction == TRANS_WRITE) {
+ rc = SQLITE_BUSY;
+ } else {
+ rc = SQLITE_OK;
+ }
+
+ /* Lock the destination database, if it is not locked already. */
+ if (SQLITE_OK == rc && p.bDestLocked == 0
+ && SQLITE_OK == (rc = sqlite3BtreeBeginTrans(p.pDest, 2))
+ ) {
+ p.bDestLocked = 1;
+ sqlite3BtreeGetMeta(p.pDest, BTREE_SCHEMA_VERSION, ref p.iDestSchema);
+ }
+
+ /* If there is no open read-transaction on the source database, open
+ ** one now. If a transaction is opened here, then it will be closed
+ ** before this function exits.
+ */
+ if (rc == SQLITE_OK && !sqlite3BtreeIsInReadTrans(p.pSrc)) {
+ rc = sqlite3BtreeBeginTrans(p.pSrc, 0);
+ bCloseTrans = 1;
+ }
+
+ /* Do not allow backup if the destination database is in WAL mode
+ ** and the page sizes are different between source and destination */
+ pgszSrc = sqlite3BtreeGetPageSize(p.pSrc);
+ pgszDest = sqlite3BtreeGetPageSize(p.pDest);
+ destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p.pDest));
+ if (SQLITE_OK == rc && destMode == PAGER_JOURNALMODE_WAL && pgszSrc != pgszDest) {
+ rc = SQLITE_READONLY;
+ }
+
+ /* Now that there is a read-lock on the source database, query the
+ ** source pager for the number of pages in the database.
+ */
+ nSrcPage = sqlite3BtreeLastPage(p.pSrc);
+ Debug.Assert(nSrcPage >= 0);
+
+ for (ii = 0; (nPage < 0 || ii < nPage) && p.iNext <= nSrcPage && 0 == rc; ii++) {
+ Pgno iSrcPg = p.iNext; /* Source page number */
+ if (iSrcPg != PENDING_BYTE_PAGE(p.pSrc.pBt)) {
+ DbPage pSrcPg = null; /* Source page object */
+ rc = sqlite3PagerGet(pSrcPager, (u32)iSrcPg, ref pSrcPg);
+ if (rc == SQLITE_OK) {
+ rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg));
+ sqlite3PagerUnref(pSrcPg);
+ }
+ }
+ p.iNext++;
+ }
+ if (rc == SQLITE_OK) {
+ p.nPagecount = nSrcPage;
+ p.nRemaining = (nSrcPage + 1 - p.iNext);
+ if (p.iNext > nSrcPage) {
+ rc = SQLITE_DONE;
+ } else if (0 == p.isAttached) {
+ attachBackupObject(p);
+ }
+ }
+
+
+ /* Update the schema version field in the destination database. This
+ ** is to make sure that the schema-version really does change in
+ ** the case where the source and destination databases have the
+ ** same schema version.
+ */
+ if (rc == SQLITE_DONE
+ && (rc = sqlite3BtreeUpdateMeta(p.pDest, 1, p.iDestSchema + 1)) == SQLITE_OK
+ ) {
+ Pgno nDestTruncate;
+ if (p.pDestDb != null) {
+ sqlite3ResetInternalSchema(p.pDestDb, -1);
+ }
+
+ /* Set nDestTruncate to the final number of pages in the destination
+ ** database. The complication here is that the destination page
+ ** size may be different to the source page size.
+ **
+ ** If the source page size is smaller than the destination page size,
+ ** round up. In this case the call to sqlite3OsTruncate() below will
+ ** fix the size of the file. However it is important to call
+ ** sqlite3PagerTruncateImage() here so that any pages in the
+ ** destination file that lie beyond the nDestTruncate page mark are
+ ** journalled by PagerCommitPhaseOne() before they are destroyed
+ ** by the file truncation.
+ */
+ Debug.Assert(pgszSrc == sqlite3BtreeGetPageSize(p.pSrc));
+ Debug.Assert(pgszDest == sqlite3BtreeGetPageSize(p.pDest));
+ if (pgszSrc < pgszDest) {
+ int ratio = pgszDest / pgszSrc;
+ nDestTruncate = (Pgno)((nSrcPage + ratio - 1) / ratio);
+ if (nDestTruncate == (int)PENDING_BYTE_PAGE(p.pDest.pBt)) {
+ nDestTruncate--;
+ }
+ } else {
+ nDestTruncate = (Pgno)(nSrcPage * (pgszSrc / pgszDest));
+ }
+ sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
+
+ if (pgszSrc < pgszDest) {
+ /* If the source page-size is smaller than the destination page-size,
+ ** two extra things may need to happen:
+ **
+ ** * The destination may need to be truncated, and
+ **
+ ** * Data stored on the pages immediately following the
+ ** pending-byte page in the source database may need to be
+ ** copied into the destination database.
+ */
+ int iSize = (int)(pgszSrc * nSrcPage);
+ sqlite3_file pFile = sqlite3PagerFile(pDestPager);
+ i64 iOff;
+ i64 iEnd;
+
+ Debug.Assert(pFile != null);
+ Debug.Assert((i64)nDestTruncate * (i64)pgszDest >= iSize || (
+ nDestTruncate == (int)(PENDING_BYTE_PAGE(p.pDest.pBt) - 1)
+ && iSize >= PENDING_BYTE && iSize <= PENDING_BYTE + pgszDest
+ ));
+
+ /* This call ensures that all data required to recreate the original
+ ** database has been stored in the journal for pDestPager and the
+ ** journal synced to disk. So at this point we may safely modify
+ ** the database file in any way, knowing that if a power failure
+ ** occurs, the original database will be reconstructed from the
+ ** journal file. */
+ rc = sqlite3PagerCommitPhaseOne(pDestPager, null, true);
+
+ /* Write the extra pages and truncate the database file as required. */
+ iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
+ for (
+ iOff = PENDING_BYTE + pgszSrc;
+ rc == SQLITE_OK && iOff < iEnd;
+ iOff += pgszSrc
+ ) {
+ PgHdr pSrcPg = null;
+ u32 iSrcPg = (u32)((iOff / pgszSrc) + 1);
+ rc = sqlite3PagerGet(pSrcPager, iSrcPg, ref pSrcPg);
+ if (rc == SQLITE_OK) {
+ byte[] zData = sqlite3PagerGetData(pSrcPg);
+ rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
+ }
+ sqlite3PagerUnref(pSrcPg);
+ }
+ if (rc == SQLITE_OK) {
+ rc = backupTruncateFile(pFile, (int)iSize);
+ }
+
+ /* Sync the database file to disk. */
+ if (rc == SQLITE_OK) {
+ rc = sqlite3PagerSync(pDestPager);
+ }
+ } else {
+ rc = sqlite3PagerCommitPhaseOne(pDestPager, null, false);
+ }
+
+ /* Finish committing the transaction to the destination database. */
+ if (SQLITE_OK == rc
+ && SQLITE_OK == (rc = sqlite3BtreeCommitPhaseTwo(p.pDest, 0))
+ ) {
+ rc = SQLITE_DONE;
+ }
+ }
+
+ /* If bCloseTrans is true, then this function opened a read transaction
+ ** on the source database. Close the read transaction here. There is
+ ** no need to check the return values of the btree methods here, as
+ ** "committing" a read-only transaction cannot fail.
+ */
+ if (bCloseTrans != 0) {
#if !NDEBUG || SQLITE_COVERAGE_TEST
- //TESTONLY( int rc2 );
- //TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p.pSrc, 0);
- //TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p.pSrc);
- int rc2;
- rc2 = sqlite3BtreeCommitPhaseOne( p.pSrc, "" );
- rc2 |= sqlite3BtreeCommitPhaseTwo( p.pSrc, 0 );
- Debug.Assert( rc2 == SQLITE_OK );
+ //TESTONLY( int rc2 );
+ //TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p.pSrc, 0);
+ //TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p.pSrc);
+ int rc2;
+ rc2 = sqlite3BtreeCommitPhaseOne(p.pSrc, "");
+ rc2 |= sqlite3BtreeCommitPhaseTwo(p.pSrc, 0);
+ Debug.Assert(rc2 == SQLITE_OK);
#else
sqlite3BtreeCommitPhaseOne(p.pSrc, null);
sqlite3BtreeCommitPhaseTwo(p.pSrc, 0);
#endif
- }
-
- if ( rc == SQLITE_IOERR_NOMEM )
- {
- rc = SQLITE_NOMEM;
- }
- p.rc = rc;
- }
- if ( p.pDestDb != null )
- {
- sqlite3_mutex_leave( p.pDestDb.mutex );
- }
- sqlite3BtreeLeave( p.pSrc );
- sqlite3_mutex_leave( p.pSrcDb.mutex );
- return rc;
-}
-
-/*
-** Release all resources associated with an sqlite3_backup* handle.
-*/
-static public int sqlite3_backup_finish( sqlite3_backup p )
-{
- sqlite3_backup pp; /* Ptr to head of pagers backup list */
- sqlite3_mutex mutex; /* Mutex to protect source database */
- int rc; /* Value to return */
-
- /* Enter the mutexes */
- if ( p == null )
- return SQLITE_OK;
- sqlite3_mutex_enter( p.pSrcDb.mutex );
- sqlite3BtreeEnter( p.pSrc );
- mutex = p.pSrcDb.mutex;
- if ( p.pDestDb != null )
- {
- sqlite3_mutex_enter( p.pDestDb.mutex );
- }
-
- /* Detach this backup from the source pager. */
- if ( p.pDestDb != null )
- {
- p.pSrc.nBackup--;
- }
- if ( p.isAttached != 0 )
- {
- pp = sqlite3PagerBackupPtr( sqlite3BtreePager( p.pSrc ) );
- while ( pp != p )
- {
- pp = ( pp ).pNext;
- }
- sqlite3BtreePager( p.pSrc ).pBackup = p.pNext;
- }
-
- /* If a transaction is still open on the Btree, roll it back. */
- sqlite3BtreeRollback( p.pDest );
-
- /* Set the error code of the destination database handle. */
- rc = ( p.rc == SQLITE_DONE ) ? SQLITE_OK : p.rc;
- sqlite3Error( p.pDestDb, rc, 0 );
+ }
+
+ if (rc == SQLITE_IOERR_NOMEM) {
+ rc = SQLITE_NOMEM;
+ }
+ p.rc = rc;
+ }
+ if (p.pDestDb != null) {
+ sqlite3_mutex_leave(p.pDestDb.mutex);
+ }
+ sqlite3BtreeLeave(p.pSrc);
+ sqlite3_mutex_leave(p.pSrcDb.mutex);
+ return rc;
+ }
- /* Exit the mutexes and free the backup context structure. */
- if ( p.pDestDb != null )
- {
- sqlite3_mutex_leave( p.pDestDb.mutex );
- }
- sqlite3BtreeLeave( p.pSrc );
- if ( p.pDestDb != null )
- {
- /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
- ** call to sqlite3_backup_init() and is destroyed by a call to
- ** sqlite3_backup_finish(). */
- //sqlite3_free( ref p );
- }
- sqlite3_mutex_leave( mutex );
- return rc;
-}
+ /*
+ ** Release all resources associated with an sqlite3_backup* handle.
+ */
+ static public int sqlite3_backup_finish(sqlite3_backup p) {
+ sqlite3_backup pp; /* Ptr to head of pagers backup list */
+ sqlite3_mutex mutex; /* Mutex to protect source database */
+ int rc; /* Value to return */
+
+ /* Enter the mutexes */
+ if (p == null)
+ return SQLITE_OK;
+ sqlite3_mutex_enter(p.pSrcDb.mutex);
+ sqlite3BtreeEnter(p.pSrc);
+ mutex = p.pSrcDb.mutex;
+ if (p.pDestDb != null) {
+ sqlite3_mutex_enter(p.pDestDb.mutex);
+ }
+
+ /* Detach this backup from the source pager. */
+ if (p.pDestDb != null) {
+ p.pSrc.nBackup--;
+ }
+ if (p.isAttached != 0) {
+ pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p.pSrc));
+ while (pp != p) {
+ pp = (pp).pNext;
+ }
+ sqlite3BtreePager(p.pSrc).pBackup = p.pNext;
+ }
+
+ /* If a transaction is still open on the Btree, roll it back. */
+ sqlite3BtreeRollback(p.pDest);
+
+ /* Set the error code of the destination database handle. */
+ rc = (p.rc == SQLITE_DONE) ? SQLITE_OK : p.rc;
+ sqlite3Error(p.pDestDb, rc, 0);
+
+ /* Exit the mutexes and free the backup context structure. */
+ if (p.pDestDb != null) {
+ sqlite3_mutex_leave(p.pDestDb.mutex);
+ }
+ sqlite3BtreeLeave(p.pSrc);
+ if (p.pDestDb != null) {
+ /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
+ ** call to sqlite3_backup_init() and is destroyed by a call to
+ ** sqlite3_backup_finish(). */
+ //sqlite3_free( ref p );
+ }
+ sqlite3_mutex_leave(mutex);
+ return rc;
+ }
-/*
-** Return the number of pages still to be backed up as of the most recent
-** call to sqlite3_backup_step().
-*/
-static int sqlite3_backup_remaining( sqlite3_backup p )
-{
- return (int)p.nRemaining;
-}
+ /*
+ ** Return the number of pages still to be backed up as of the most recent
+ ** call to sqlite3_backup_step().
+ */
+ static int sqlite3_backup_remaining(sqlite3_backup p) {
+ return (int)p.nRemaining;
+ }
-/*
-** Return the total number of pages in the source database as of the most
-** recent call to sqlite3_backup_step().
-*/
-static int sqlite3_backup_pagecount( sqlite3_backup p )
-{
- return (int)p.nPagecount;
-}
+ /*
+ ** Return the total number of pages in the source database as of the most
+ ** recent call to sqlite3_backup_step().
+ */
+ static int sqlite3_backup_pagecount(sqlite3_backup p) {
+ return (int)p.nPagecount;
+ }
-/*
-** This function is called after the contents of page iPage of the
-** source database have been modified. If page iPage has already been
-** copied into the destination database, then the data written to the
-** destination is now invalidated. The destination copy of iPage needs
-** to be updated with the new data before the backup operation is
-** complete.
-**
-** It is assumed that the mutex associated with the BtShared object
-** corresponding to the source database is held when this function is
-** called.
-*/
-static void sqlite3BackupUpdate( sqlite3_backup pBackup, Pgno iPage, byte[] aData )
-{
- sqlite3_backup p; /* Iterator variable */
- for ( p = pBackup; p != null; p = p.pNext )
- {
- Debug.Assert( sqlite3_mutex_held( p.pSrc.pBt.mutex ) );
- if ( !isFatalError( p.rc ) && iPage < p.iNext )
- {
- /* The backup process p has already copied page iPage. But now it
- ** has been modified by a transaction on the source pager. Copy
- ** the new data into the backup.
- */
- int rc;
- Debug.Assert( p.pDestDb != null );
- sqlite3_mutex_enter( p.pDestDb.mutex );
- rc = backupOnePage( p, iPage, aData );
- sqlite3_mutex_leave( p.pDestDb.mutex );
- Debug.Assert( rc != SQLITE_BUSY && rc != SQLITE_LOCKED );
- if ( rc != SQLITE_OK )
- {
- p.rc = rc;
- }
- }
- }
-}
+ /*
+ ** This function is called after the contents of page iPage of the
+ ** source database have been modified. If page iPage has already been
+ ** copied into the destination database, then the data written to the
+ ** destination is now invalidated. The destination copy of iPage needs
+ ** to be updated with the new data before the backup operation is
+ ** complete.
+ **
+ ** It is assumed that the mutex associated with the BtShared object
+ ** corresponding to the source database is held when this function is
+ ** called.
+ */
+ static void sqlite3BackupUpdate(sqlite3_backup pBackup, Pgno iPage, byte[] aData) {
+ sqlite3_backup p; /* Iterator variable */
+ for (p = pBackup; p != null; p = p.pNext) {
+ Debug.Assert(sqlite3_mutex_held(p.pSrc.pBt.mutex));
+ if (!isFatalError(p.rc) && iPage < p.iNext) {
+ /* The backup process p has already copied page iPage. But now it
+ ** has been modified by a transaction on the source pager. Copy
+ ** the new data into the backup.
+ */
+ int rc;
+ Debug.Assert(p.pDestDb != null);
+ sqlite3_mutex_enter(p.pDestDb.mutex);
+ rc = backupOnePage(p, iPage, aData);
+ sqlite3_mutex_leave(p.pDestDb.mutex);
+ Debug.Assert(rc != SQLITE_BUSY && rc != SQLITE_LOCKED);
+ if (rc != SQLITE_OK) {
+ p.rc = rc;
+ }
+ }
+ }
+ }
-/*
-** Restart the backup process. This is called when the pager layer
-** detects that the database has been modified by an external database
-** connection. In this case there is no way of knowing which of the
-** pages that have been copied into the destination database are still
-** valid and which are not, so the entire process needs to be restarted.
-**
-** It is assumed that the mutex associated with the BtShared object
-** corresponding to the source database is held when this function is
-** called.
-*/
-static void sqlite3BackupRestart( sqlite3_backup pBackup )
-{
- sqlite3_backup p; /* Iterator variable */
- for ( p = pBackup; p != null; p = p.pNext )
- {
- Debug.Assert( sqlite3_mutex_held( p.pSrc.pBt.mutex ) );
- p.iNext = 1;
- }
-}
+ /*
+ ** Restart the backup process. This is called when the pager layer
+ ** detects that the database has been modified by an external database
+ ** connection. In this case there is no way of knowing which of the
+ ** pages that have been copied into the destination database are still
+ ** valid and which are not, so the entire process needs to be restarted.
+ **
+ ** It is assumed that the mutex associated with the BtShared object
+ ** corresponding to the source database is held when this function is
+ ** called.
+ */
+ static void sqlite3BackupRestart(sqlite3_backup pBackup) {
+ sqlite3_backup p; /* Iterator variable */
+ for (p = pBackup; p != null; p = p.pNext) {
+ Debug.Assert(sqlite3_mutex_held(p.pSrc.pBt.mutex));
+ p.iNext = 1;
+ }
+ }
#if !SQLITE_OMIT_VACUUM
-/*
-** Copy the complete content of pBtFrom into pBtTo. A transaction
-** must be active for both files.
-**
-** The size of file pTo may be reduced by this operation. If anything
-** goes wrong, the transaction on pTo is rolled back. If successful, the
-** transaction is committed before returning.
-*/
-static int sqlite3BtreeCopyFile( Btree pTo, Btree pFrom )
-{
- int rc;
- sqlite3_backup b;
- sqlite3BtreeEnter( pTo );
- sqlite3BtreeEnter( pFrom );
-
- /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
- ** to 0. This is used by the implementations of sqlite3_backup_step()
- ** and sqlite3_backup_finish() to detect that they are being called
- ** from this function, not directly by the user.
- */
- b = new sqlite3_backup();// memset( &b, 0, sizeof( b ) );
- b.pSrcDb = pFrom.db;
- b.pSrc = pFrom;
- b.pDest = pTo;
- b.iNext = 1;
-
- /* 0x7FFFFFFF is the hard limit for the number of pages in a database
- ** file. By passing this as the number of pages to copy to
- ** sqlite3_backup_step(), we can guarantee that the copy finishes
- ** within a single call (unless an error occurs). The Debug.Assert() statement
- ** checks this assumption - (p.rc) should be set to either SQLITE_DONE
- ** or an error code.
- */
- sqlite3_backup_step( b, 0x7FFFFFFF );
- Debug.Assert( b.rc != SQLITE_OK );
- rc = sqlite3_backup_finish( b );
- if ( rc == SQLITE_OK )
- {
- pTo.pBt.pageSizeFixed = false;
- }
-
- sqlite3BtreeLeave( pFrom );
- sqlite3BtreeLeave( pTo );
- return rc;
-}
+ /*
+ ** Copy the complete content of pBtFrom into pBtTo. A transaction
+ ** must be active for both files.
+ **
+ ** The size of file pTo may be reduced by this operation. If anything
+ ** goes wrong, the transaction on pTo is rolled back. If successful, the
+ ** transaction is committed before returning.
+ */
+ static int sqlite3BtreeCopyFile(Btree pTo, Btree pFrom) {
+ int rc;
+ sqlite3_backup b;
+ sqlite3BtreeEnter(pTo);
+ sqlite3BtreeEnter(pFrom);
+
+ /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
+ ** to 0. This is used by the implementations of sqlite3_backup_step()
+ ** and sqlite3_backup_finish() to detect that they are being called
+ ** from this function, not directly by the user.
+ */
+ b = new sqlite3_backup();// memset( &b, 0, sizeof( b ) );
+ b.pSrcDb = pFrom.db;
+ b.pSrc = pFrom;
+ b.pDest = pTo;
+ b.iNext = 1;
+
+ /* 0x7FFFFFFF is the hard limit for the number of pages in a database
+ ** file. By passing this as the number of pages to copy to
+ ** sqlite3_backup_step(), we can guarantee that the copy finishes
+ ** within a single call (unless an error occurs). The Debug.Assert() statement
+ ** checks this assumption - (p.rc) should be set to either SQLITE_DONE
+ ** or an error code.
+ */
+ sqlite3_backup_step(b, 0x7FFFFFFF);
+ Debug.Assert(b.rc != SQLITE_OK);
+ rc = sqlite3_backup_finish(b);
+ if (rc == SQLITE_OK) {
+ pTo.pBt.pageSizeFixed = false;
+ }
+
+ sqlite3BtreeLeave(pFrom);
+ sqlite3BtreeLeave(pTo);
+ return rc;
+ }
#endif //* SQLITE_OMIT_VACUUM */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/bitvec_c.cs b/Src/IronPython.SQLite/c#sqlite/bitvec_c.cs
index 6b7414ba0..7df896883 100644
--- a/Src/IronPython.SQLite/c#sqlite/bitvec_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/bitvec_c.cs
@@ -1,534 +1,479 @@
using System;
using System.Diagnostics;
-using System.Runtime.InteropServices;
-using Pgno = System.UInt32;
+using BITVEC_TELEM = System.Byte;
using i64 = System.Int64;
using u32 = System.UInt32;
-using BITVEC_TELEM = System.Byte;
-namespace Community.CsharpSqlite
-{
-
- public partial class Sqlite3
- {
-/*
-** 2008 February 16
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-** This file implements an object that represents a fixed-length
-** bitmap. Bits are numbered starting with 1.
-**
-** A bitmap is used to record which pages of a database file have been
-** journalled during a transaction, or which pages have the "dont-write"
-** property. Usually only a few pages are meet either condition.
-** So the bitmap is usually sparse and has low cardinality.
-** But sometimes (for example when during a DROP of a large table) most
-** or all of the pages in a database can get journalled. In those cases,
-** the bitmap becomes dense with high cardinality. The algorithm needs
-** to handle both cases well.
-**
-** The size of the bitmap is fixed when the object is created.
-**
-** All bits are clear when the bitmap is created. Individual bits
-** may be set or cleared one at a time.
-**
-** Test operations are about 100 times more common that set operations.
-** Clear operations are exceedingly rare. There are usually between
-** 5 and 500 set operations per Bitvec object, though the number of sets can
-** sometimes grow into tens of thousands or larger. The size of the
-** Bitvec object is the number of pages in the database file at the
-** start of a transaction, and is thus usually less than a few thousand,
-** but can be as large as 2 billion for a really big database.
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
-**
-*************************************************************************
-*/
-//#include "sqliteInt.h"
-
-/* Size of the Bitvec structure in bytes. */
-static int BITVEC_SZ = 512;
-
-
-/* Round the union size down to the nearest pointer boundary, since that's how
-** it will be aligned within the Bitvec struct. */
-//#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
-static int BITVEC_USIZE = ( ( ( BITVEC_SZ - ( 3 * sizeof( u32 ) ) ) / 4 ) * 4 );
-
-/* Type of the array "element" for the bitmap representation.
-** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
-** Setting this to the "natural word" size of your CPU may improve
-** performance. */
-//#define BITVEC_TELEM u8
-//using BITVEC_TELEM = System.Byte;
-
-/* Size, in bits, of the bitmap element. */
-//#define BITVEC_SZELEM 8
-const int BITVEC_SZELEM = 8;
-
-/* Number of elements in a bitmap array. */
-//#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
-static int BITVEC_NELEM = (int)( BITVEC_USIZE / sizeof( BITVEC_TELEM ) );
-
-/* Number of bits in the bitmap array. */
-//#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
-static int BITVEC_NBIT = ( BITVEC_NELEM * BITVEC_SZELEM );
-
-/* Number of u32 values in hash table. */
-//#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
-static u32 BITVEC_NINT = (u32)( BITVEC_USIZE / sizeof( u32 ) );
-
-/* Maximum number of entries in hash table before
-** sub-dividing and re-hashing. */
-//#define BITVEC_MXHASH (BITVEC_NINT/2)
-static int BITVEC_MXHASH = (int)( BITVEC_NINT / 2 );
-
-/* Hashing function for the aHash representation.
-** Empirical testing showed that the *37 multiplier
-** (an arbitrary prime)in the hash function provided
-** no fewer collisions than the no-op *1. */
-//#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
-static u32 BITVEC_HASH( u32 X )
-{
- return (u32)( ( ( X ) * 1 ) % BITVEC_NINT );
-}
+namespace Community.CsharpSqlite {
+
+ public partial class Sqlite3 {
+ /*
+ ** 2008 February 16
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file implements an object that represents a fixed-length
+ ** bitmap. Bits are numbered starting with 1.
+ **
+ ** A bitmap is used to record which pages of a database file have been
+ ** journalled during a transaction, or which pages have the "dont-write"
+ ** property. Usually only a few pages are meet either condition.
+ ** So the bitmap is usually sparse and has low cardinality.
+ ** But sometimes (for example when during a DROP of a large table) most
+ ** or all of the pages in a database can get journalled. In those cases,
+ ** the bitmap becomes dense with high cardinality. The algorithm needs
+ ** to handle both cases well.
+ **
+ ** The size of the bitmap is fixed when the object is created.
+ **
+ ** All bits are clear when the bitmap is created. Individual bits
+ ** may be set or cleared one at a time.
+ **
+ ** Test operations are about 100 times more common that set operations.
+ ** Clear operations are exceedingly rare. There are usually between
+ ** 5 and 500 set operations per Bitvec object, though the number of sets can
+ ** sometimes grow into tens of thousands or larger. The size of the
+ ** Bitvec object is the number of pages in the database file at the
+ ** start of a transaction, and is thus usually less than a few thousand,
+ ** but can be as large as 2 billion for a really big database.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
+
+ /* Size of the Bitvec structure in bytes. */
+ static int BITVEC_SZ = 512;
+
+
+ /* Round the union size down to the nearest pointer boundary, since that's how
+ ** it will be aligned within the Bitvec struct. */
+ //#define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
+ static int BITVEC_USIZE = (((BITVEC_SZ - (3 * sizeof(u32))) / 4) * 4);
+
+ /* Type of the array "element" for the bitmap representation.
+ ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
+ ** Setting this to the "natural word" size of your CPU may improve
+ ** performance. */
+ //#define BITVEC_TELEM u8
+ //using BITVEC_TELEM = System.Byte;
+
+ /* Size, in bits, of the bitmap element. */
+ //#define BITVEC_SZELEM 8
+ const int BITVEC_SZELEM = 8;
+
+ /* Number of elements in a bitmap array. */
+ //#define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
+ static int BITVEC_NELEM = (int)(BITVEC_USIZE / sizeof(BITVEC_TELEM));
+
+ /* Number of bits in the bitmap array. */
+ //#define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
+ static int BITVEC_NBIT = (BITVEC_NELEM * BITVEC_SZELEM);
+
+ /* Number of u32 values in hash table. */
+ //#define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
+ static u32 BITVEC_NINT = (u32)(BITVEC_USIZE / sizeof(u32));
+
+ /* Maximum number of entries in hash table before
+ ** sub-dividing and re-hashing. */
+ //#define BITVEC_MXHASH (BITVEC_NINT/2)
+ static int BITVEC_MXHASH = (int)(BITVEC_NINT / 2);
+
+ /* Hashing function for the aHash representation.
+ ** Empirical testing showed that the *37 multiplier
+ ** (an arbitrary prime)in the hash function provided
+ ** no fewer collisions than the no-op *1. */
+ //#define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
+ static u32 BITVEC_HASH(u32 X) {
+ return (u32)(((X) * 1) % BITVEC_NINT);
+ }
-static int BITVEC_NPTR = (int)( BITVEC_USIZE / 4 );//sizeof(Bitvec *));
-
-
-/*
-** A bitmap is an instance of the following structure.
-**
-** This bitmap records the existence of zero or more bits
-** with values between 1 and iSize, inclusive.
-**
-** There are three possible representations of the bitmap.
-** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
-** bitmap. The least significant bit is bit 1.
-**
-** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
-** a hash table that will hold up to BITVEC_MXHASH distinct values.
-**
-** Otherwise, the value i is redirected into one of BITVEC_NPTR
-** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
-** handles up to iDivisor separate values of i. apSub[0] holds
-** values between 1 and iDivisor. apSub[1] holds values between
-** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
-** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
-** to hold deal with values between 1 and iDivisor.
-*/
-public class _u
-{
- public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */
- public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */
- public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */
-}
-public class Bitvec
-{
- public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
- public u32 nSet; /* Number of bits that are set - only valid for aHash
+ static int BITVEC_NPTR = (int)(BITVEC_USIZE / 4);//sizeof(Bitvec *));
+
+
+ /*
+ ** A bitmap is an instance of the following structure.
+ **
+ ** This bitmap records the existence of zero or more bits
+ ** with values between 1 and iSize, inclusive.
+ **
+ ** There are three possible representations of the bitmap.
+ ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
+ ** bitmap. The least significant bit is bit 1.
+ **
+ ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
+ ** a hash table that will hold up to BITVEC_MXHASH distinct values.
+ **
+ ** Otherwise, the value i is redirected into one of BITVEC_NPTR
+ ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
+ ** handles up to iDivisor separate values of i. apSub[0] holds
+ ** values between 1 and iDivisor. apSub[1] holds values between
+ ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
+ ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
+ ** to hold deal with values between 1 and iDivisor.
+ */
+ public class _u {
+ public BITVEC_TELEM[] aBitmap = new byte[BITVEC_NELEM]; /* Bitmap representation */
+ public u32[] aHash = new u32[BITVEC_NINT]; /* Hash table representation */
+ public Bitvec[] apSub = new Bitvec[BITVEC_NPTR]; /* Recursive representation */
+ }
+ public class Bitvec {
+ public u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
+ public u32 nSet; /* Number of bits that are set - only valid for aHash
** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
** this would be 125. */
- public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
- /* Should >=0 for apSub element. */
- /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
- /* For a BITVEC_SZ of 512, this would be 34,359,739. */
- public _u u = new _u();
-
- public static implicit operator bool( Bitvec b )
- {
- return ( b != null );
- }
-};
-
-/*
-** Create a new bitmap object able to handle bits between 0 and iSize,
-** inclusive. Return a pointer to the new object. Return NULL if
-** malloc fails.
-*/
-static Bitvec sqlite3BitvecCreate( u32 iSize )
-{
- Bitvec p;
- //Debug.Assert( sizeof(p)==BITVEC_SZ );
- p = new Bitvec();//sqlite3MallocZero( sizeof(p) );
- if ( p != null )
- {
- p.iSize = iSize;
- }
- return p;
-}
+ public u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
+ /* Should >=0 for apSub element. */
+ /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
+ /* For a BITVEC_SZ of 512, this would be 34,359,739. */
+ public _u u = new _u();
+
+ public static implicit operator bool(Bitvec b) {
+ return (b != null);
+ }
+ };
+
+ /*
+ ** Create a new bitmap object able to handle bits between 0 and iSize,
+ ** inclusive. Return a pointer to the new object. Return NULL if
+ ** malloc fails.
+ */
+ static Bitvec sqlite3BitvecCreate(u32 iSize) {
+ Bitvec p;
+ //Debug.Assert( sizeof(p)==BITVEC_SZ );
+ p = new Bitvec();//sqlite3MallocZero( sizeof(p) );
+ if (p != null) {
+ p.iSize = iSize;
+ }
+ return p;
+ }
-/*
-** Check to see if the i-th bit is set. Return true or false.
-** If p is NULL (if the bitmap has not been created) or if
-** i is out of range, then return false.
-*/
-static int sqlite3BitvecTest( Bitvec p, u32 i )
-{
- if ( p == null || i == 0 )
- return 0;
- if ( i > p.iSize )
- return 0;
- i--;
- while ( p.iDivisor != 0 )
- {
- u32 bin = i / p.iDivisor;
- i = i % p.iDivisor;
- p = p.u.apSub[bin];
- if ( null == p )
- {
- return 0;
- }
- }
- if ( p.iSize <= BITVEC_NBIT )
- {
- return ( ( p.u.aBitmap[i / BITVEC_SZELEM] & ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) ) != 0 ) ? 1 : 0;
- }
- else
- {
- u32 h = BITVEC_HASH( i++ );
- while ( p.u.aHash[h] != 0 )
- {
- if ( p.u.aHash[h] == i )
- return 1;
- h = ( h + 1 ) % BITVEC_NINT;
- }
- return 0;
- }
-}
+ /*
+ ** Check to see if the i-th bit is set. Return true or false.
+ ** If p is NULL (if the bitmap has not been created) or if
+ ** i is out of range, then return false.
+ */
+ static int sqlite3BitvecTest(Bitvec p, u32 i) {
+ if (p == null || i == 0)
+ return 0;
+ if (i > p.iSize)
+ return 0;
+ i--;
+ while (p.iDivisor != 0) {
+ u32 bin = i / p.iDivisor;
+ i = i % p.iDivisor;
+ p = p.u.apSub[bin];
+ if (null == p) {
+ return 0;
+ }
+ }
+ if (p.iSize <= BITVEC_NBIT) {
+ return ((p.u.aBitmap[i / BITVEC_SZELEM] & (1 << (int)(i & (BITVEC_SZELEM - 1)))) != 0) ? 1 : 0;
+ } else {
+ u32 h = BITVEC_HASH(i++);
+ while (p.u.aHash[h] != 0) {
+ if (p.u.aHash[h] == i)
+ return 1;
+ h = (h + 1) % BITVEC_NINT;
+ }
+ return 0;
+ }
+ }
-/*
-** Set the i-th bit. Return 0 on success and an error code if
-** anything goes wrong.
-**
-** This routine might cause sub-bitmaps to be allocated. Failing
-** to get the memory needed to hold the sub-bitmap is the only
-** that can go wrong with an insert, assuming p and i are valid.
-**
-** The calling function must ensure that p is a valid Bitvec object
-** and that the value for "i" is within range of the Bitvec object.
-** Otherwise the behavior is undefined.
-*/
-static int sqlite3BitvecSet( Bitvec p, u32 i )
-{
- u32 h;
- if ( p == null )
- return SQLITE_OK;
- Debug.Assert( i > 0 );
- Debug.Assert( i <= p.iSize );
- i--;
- while ( ( p.iSize > BITVEC_NBIT ) && p.iDivisor != 0 )
- {
- u32 bin = i / p.iDivisor;
- i = i % p.iDivisor;
- if ( p.u.apSub[bin] == null )
- {
- p.u.apSub[bin] = sqlite3BitvecCreate( p.iDivisor );
- //if ( p.u.apSub[bin] == null )
- // return SQLITE_NOMEM;
- }
- p = p.u.apSub[bin];
- }
- if ( p.iSize <= BITVEC_NBIT )
- {
- p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) );
- return SQLITE_OK;
- }
- h = BITVEC_HASH( i++ );
- /* if there wasn't a hash collision, and this doesn't */
- /* completely fill the hash, then just add it without */
- /* worring about sub-dividing and re-hashing. */
- if ( 0 == p.u.aHash[h] )
- {
- if ( p.nSet < ( BITVEC_NINT - 1 ) )
- {
- goto bitvec_set_end;
- }
- else
- {
- goto bitvec_set_rehash;
- }
- }
- /* there was a collision, check to see if it's already */
- /* in hash, if not, try to find a spot for it */
- do
- {
- if ( p.u.aHash[h] == i )
- return SQLITE_OK;
- h++;
- if ( h >= BITVEC_NINT )
- h = 0;
- } while ( p.u.aHash[h] != 0 );
-/* we didn't find it in the hash. h points to the first */
-/* available free spot. check to see if this is going to */
-/* make our hash too "full". */
-bitvec_set_rehash:
- if ( p.nSet >= BITVEC_MXHASH )
- {
- u32 j;
- int rc;
- u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
- //if ( aiValues == null )
- //{
- // return SQLITE_NOMEM;
- //}
- //else
- {
-
- Buffer.BlockCopy( p.u.aHash, 0, aiValues, 0, aiValues.Length * ( sizeof( u32 ) ) );// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
- p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub));
- p.iDivisor = (u32)( ( p.iSize + BITVEC_NPTR - 1 ) / BITVEC_NPTR );
- rc = sqlite3BitvecSet( p, i );
- for ( j = 0; j < BITVEC_NINT; j++ )
- {
- if ( aiValues[j] != 0 )
- rc |= sqlite3BitvecSet( p, aiValues[j] );
- }
- //sqlite3StackFree( null, aiValues );
- return rc;
- }
- }
-bitvec_set_end:
- p.nSet++;
- p.u.aHash[h] = i;
- return SQLITE_OK;
-}
+ /*
+ ** Set the i-th bit. Return 0 on success and an error code if
+ ** anything goes wrong.
+ **
+ ** This routine might cause sub-bitmaps to be allocated. Failing
+ ** to get the memory needed to hold the sub-bitmap is the only
+ ** that can go wrong with an insert, assuming p and i are valid.
+ **
+ ** The calling function must ensure that p is a valid Bitvec object
+ ** and that the value for "i" is within range of the Bitvec object.
+ ** Otherwise the behavior is undefined.
+ */
+ static int sqlite3BitvecSet(Bitvec p, u32 i) {
+ u32 h;
+ if (p == null)
+ return SQLITE_OK;
+ Debug.Assert(i > 0);
+ Debug.Assert(i <= p.iSize);
+ i--;
+ while ((p.iSize > BITVEC_NBIT) && p.iDivisor != 0) {
+ u32 bin = i / p.iDivisor;
+ i = i % p.iDivisor;
+ if (p.u.apSub[bin] == null) {
+ p.u.apSub[bin] = sqlite3BitvecCreate(p.iDivisor);
+ //if ( p.u.apSub[bin] == null )
+ // return SQLITE_NOMEM;
+ }
+ p = p.u.apSub[bin];
+ }
+ if (p.iSize <= BITVEC_NBIT) {
+ p.u.aBitmap[i / BITVEC_SZELEM] |= (byte)(1 << (int)(i & (BITVEC_SZELEM - 1)));
+ return SQLITE_OK;
+ }
+ h = BITVEC_HASH(i++);
+ /* if there wasn't a hash collision, and this doesn't */
+ /* completely fill the hash, then just add it without */
+ /* worring about sub-dividing and re-hashing. */
+ if (0 == p.u.aHash[h]) {
+ if (p.nSet < (BITVEC_NINT - 1)) {
+ goto bitvec_set_end;
+ } else {
+ goto bitvec_set_rehash;
+ }
+ }
+ /* there was a collision, check to see if it's already */
+ /* in hash, if not, try to find a spot for it */
+ do {
+ if (p.u.aHash[h] == i)
+ return SQLITE_OK;
+ h++;
+ if (h >= BITVEC_NINT)
+ h = 0;
+ } while (p.u.aHash[h] != 0);
+ /* we didn't find it in the hash. h points to the first */
+ /* available free spot. check to see if this is going to */
+ /* make our hash too "full". */
+ bitvec_set_rehash:
+ if (p.nSet >= BITVEC_MXHASH) {
+ u32 j;
+ int rc;
+ u32[] aiValues = new u32[BITVEC_NINT];// = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
+ //if ( aiValues == null )
+ //{
+ // return SQLITE_NOMEM;
+ //}
+ //else
+ {
+
+ Buffer.BlockCopy(p.u.aHash, 0, aiValues, 0, aiValues.Length * (sizeof(u32)));// memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
+ p.u.apSub = new Bitvec[BITVEC_NPTR];//memset(p->u.apSub, 0, sizeof(p->u.apSub));
+ p.iDivisor = (u32)((p.iSize + BITVEC_NPTR - 1) / BITVEC_NPTR);
+ rc = sqlite3BitvecSet(p, i);
+ for (j = 0; j < BITVEC_NINT; j++) {
+ if (aiValues[j] != 0)
+ rc |= sqlite3BitvecSet(p, aiValues[j]);
+ }
+ //sqlite3StackFree( null, aiValues );
+ return rc;
+ }
+ }
+ bitvec_set_end:
+ p.nSet++;
+ p.u.aHash[h] = i;
+ return SQLITE_OK;
+ }
-/*
-** Clear the i-th bit.
-**
-** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
-** that BitvecClear can use to rebuilt its hash table.
-*/
-static void sqlite3BitvecClear( Bitvec p, u32 i, u32[] pBuf )
-{
- if ( p == null )
- return;
- Debug.Assert( i > 0 );
- i--;
- while ( p.iDivisor != 0 )
- {
- u32 bin = i / p.iDivisor;
- i = i % p.iDivisor;
- p = p.u.apSub[bin];
- if ( null == p )
- {
- return;
- }
- }
- if ( p.iSize <= BITVEC_NBIT )
- {
- p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~( ( 1 << (int)( i & ( BITVEC_SZELEM - 1 ) ) ) );
- }
- else
- {
- u32 j;
- u32[] aiValues = pBuf;
- Array.Copy( p.u.aHash, aiValues, p.u.aHash.Length );//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
- p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash));
- p.nSet = 0;
- for ( j = 0; j < BITVEC_NINT; j++ )
- {
- if ( aiValues[j] != 0 && aiValues[j] != ( i + 1 ) )
- {
- u32 h = BITVEC_HASH( aiValues[j] - 1 );
- p.nSet++;
- while ( p.u.aHash[h] != 0 )
- {
- h++;
- if ( h >= BITVEC_NINT )
- h = 0;
+ /*
+ ** Clear the i-th bit.
+ **
+ ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
+ ** that BitvecClear can use to rebuilt its hash table.
+ */
+ static void sqlite3BitvecClear(Bitvec p, u32 i, u32[] pBuf) {
+ if (p == null)
+ return;
+ Debug.Assert(i > 0);
+ i--;
+ while (p.iDivisor != 0) {
+ u32 bin = i / p.iDivisor;
+ i = i % p.iDivisor;
+ p = p.u.apSub[bin];
+ if (null == p) {
+ return;
+ }
+ }
+ if (p.iSize <= BITVEC_NBIT) {
+ p.u.aBitmap[i / BITVEC_SZELEM] &= (byte)~((1 << (int)(i & (BITVEC_SZELEM - 1))));
+ } else {
+ u32 j;
+ u32[] aiValues = pBuf;
+ Array.Copy(p.u.aHash, aiValues, p.u.aHash.Length);//memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
+ p.u.aHash = new u32[aiValues.Length];// memset(p->u.aHash, 0, sizeof(p->u.aHash));
+ p.nSet = 0;
+ for (j = 0; j < BITVEC_NINT; j++) {
+ if (aiValues[j] != 0 && aiValues[j] != (i + 1)) {
+ u32 h = BITVEC_HASH(aiValues[j] - 1);
+ p.nSet++;
+ while (p.u.aHash[h] != 0) {
+ h++;
+ if (h >= BITVEC_NINT)
+ h = 0;
+ }
+ p.u.aHash[h] = aiValues[j];
+ }
+ }
+ }
}
- p.u.aHash[h] = aiValues[j];
- }
- }
- }
-}
-/*
-** Destroy a bitmap object. Reclaim all memory used.
-*/
-static void sqlite3BitvecDestroy( ref Bitvec p )
-{
- if ( p == null )
- return;
- if ( p.iDivisor != 0 )
- {
- u32 i;
- for ( i = 0; i < BITVEC_NPTR; i++ )
- {
- sqlite3BitvecDestroy( ref p.u.apSub[i] );
- }
- }
- //sqlite3_free( ref p );
-}
+ /*
+ ** Destroy a bitmap object. Reclaim all memory used.
+ */
+ static void sqlite3BitvecDestroy(ref Bitvec p) {
+ if (p == null)
+ return;
+ if (p.iDivisor != 0) {
+ u32 i;
+ for (i = 0; i < BITVEC_NPTR; i++) {
+ sqlite3BitvecDestroy(ref p.u.apSub[i]);
+ }
+ }
+ //sqlite3_free( ref p );
+ }
-/*
-** Return the value of the iSize parameter specified when Bitvec *p
-** was created.
-*/
-static u32 sqlite3BitvecSize( Bitvec p )
-{
- return p.iSize;
-}
+ /*
+ ** Return the value of the iSize parameter specified when Bitvec *p
+ ** was created.
+ */
+ static u32 sqlite3BitvecSize(Bitvec p) {
+ return p.iSize;
+ }
#if !SQLITE_OMIT_BUILTIN_TEST
-/*
-** Let V[] be an array of unsigned characters sufficient to hold
-** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7))
-static void SETBIT( byte[] V, int I )
-{
- V[I >> 3] |= (byte)( 1 << ( I & 7 ) );
-}
-
-//#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
-static void CLEARBIT( byte[] V, int I )
-{
- V[I >> 3] &= (byte)~( 1 << ( I & 7 ) );
-}
+ /*
+ ** Let V[] be an array of unsigned characters sufficient to hold
+ ** up to N bits. Let I be an integer between 0 and N. 0<=I>3] |= (1<<(I&7))
+ static void SETBIT(byte[] V, int I) {
+ V[I >> 3] |= (byte)(1 << (I & 7));
+ }
-//#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
-static int TESTBIT( byte[] V, int I )
-{
- return ( V[I >> 3] & ( 1 << ( I & 7 ) ) ) != 0 ? 1 : 0;
-}
+ //#define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
+ static void CLEARBIT(byte[] V, int I) {
+ V[I >> 3] &= (byte)~(1 << (I & 7));
+ }
-/*
-** This routine runs an extensive test of the Bitvec code.
-**
-** The input is an array of integers that acts as a program
-** to test the Bitvec. The integers are opcodes followed
-** by 0, 1, or 3 operands, depending on the opcode. Another
-** opcode follows immediately after the last operand.
-**
-** There are 6 opcodes numbered from 0 through 5. 0 is the
-** "halt" opcode and causes the test to end.
-**
-** 0 Halt and return the number of errors
-** 1 N S X Set N bits beginning with S and incrementing by X
-** 2 N S X Clear N bits beginning with S and incrementing by X
-** 3 N Set N randomly chosen bits
-** 4 N Clear N randomly chosen bits
-** 5 N S X Set N bits from S increment X in array only, not in bitvec
-**
-** The opcodes 1 through 4 perform set and clear operations are performed
-** on both a Bitvec object and on a linear array of bits obtained from malloc.
-** Opcode 5 works on the linear array only, not on the Bitvec.
-** Opcode 5 is used to deliberately induce a fault in order to
-** confirm that error detection works.
-**
-** At the conclusion of the test the linear array is compared
-** against the Bitvec object. If there are any differences,
-** an error is returned. If they are the same, zero is returned.
-**
-** If a memory allocation error occurs, return -1.
-*/
-static int sqlite3BitvecBuiltinTest( u32 sz, int[] aOp )
-{
- Bitvec pBitvec = null;
- byte[] pV = null;
- int rc = -1;
- int i, nx, pc, op;
- u32[] pTmpSpace;
-
- /* Allocate the Bitvec to be tested and a linear array of
- ** bits to act as the reference */
- pBitvec = sqlite3BitvecCreate( sz );
- pV = sqlite3_malloc( (int)( sz + 7 ) / 8 + 1 );
- pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ );
- if ( pBitvec == null || pV == null || pTmpSpace == null )
- goto bitvec_end;
- Array.Clear( pV, 0, (int)( sz + 7 ) / 8 + 1 );// memset( pV, 0, ( sz + 7 ) / 8 + 1 );
-
- /* NULL pBitvec tests */
- sqlite3BitvecSet( null, (u32)1 );
- sqlite3BitvecClear( null, 1, pTmpSpace );
-
- /* Run the program */
- pc = 0;
- while ( ( op = aOp[pc] ) != 0 )
- {
- switch ( op )
- {
- case 1:
- case 2:
- case 5:
- {
- nx = 4;
- i = aOp[pc + 2] - 1;
- aOp[pc + 2] += aOp[pc + 3];
- break;
+ //#define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
+ static int TESTBIT(byte[] V, int I) {
+ return (V[I >> 3] & (1 << (I & 7))) != 0 ? 1 : 0;
}
- case 3:
- case 4:
- default:
- {
- nx = 2;
- i64 i64Temp = 0;
- sqlite3_randomness( sizeof( i64 ), ref i64Temp );
- i = (int)i64Temp;
- break;
+
+ /*
+ ** This routine runs an extensive test of the Bitvec code.
+ **
+ ** The input is an array of integers that acts as a program
+ ** to test the Bitvec. The integers are opcodes followed
+ ** by 0, 1, or 3 operands, depending on the opcode. Another
+ ** opcode follows immediately after the last operand.
+ **
+ ** There are 6 opcodes numbered from 0 through 5. 0 is the
+ ** "halt" opcode and causes the test to end.
+ **
+ ** 0 Halt and return the number of errors
+ ** 1 N S X Set N bits beginning with S and incrementing by X
+ ** 2 N S X Clear N bits beginning with S and incrementing by X
+ ** 3 N Set N randomly chosen bits
+ ** 4 N Clear N randomly chosen bits
+ ** 5 N S X Set N bits from S increment X in array only, not in bitvec
+ **
+ ** The opcodes 1 through 4 perform set and clear operations are performed
+ ** on both a Bitvec object and on a linear array of bits obtained from malloc.
+ ** Opcode 5 works on the linear array only, not on the Bitvec.
+ ** Opcode 5 is used to deliberately induce a fault in order to
+ ** confirm that error detection works.
+ **
+ ** At the conclusion of the test the linear array is compared
+ ** against the Bitvec object. If there are any differences,
+ ** an error is returned. If they are the same, zero is returned.
+ **
+ ** If a memory allocation error occurs, return -1.
+ */
+ static int sqlite3BitvecBuiltinTest(u32 sz, int[] aOp) {
+ Bitvec pBitvec = null;
+ byte[] pV = null;
+ int rc = -1;
+ int i, nx, pc, op;
+ u32[] pTmpSpace;
+
+ /* Allocate the Bitvec to be tested and a linear array of
+ ** bits to act as the reference */
+ pBitvec = sqlite3BitvecCreate(sz);
+ pV = sqlite3_malloc((int)(sz + 7) / 8 + 1);
+ pTmpSpace = new u32[BITVEC_SZ];// sqlite3_malloc( BITVEC_SZ );
+ if (pBitvec == null || pV == null || pTmpSpace == null)
+ goto bitvec_end;
+ Array.Clear(pV, 0, (int)(sz + 7) / 8 + 1);// memset( pV, 0, ( sz + 7 ) / 8 + 1 );
+
+ /* NULL pBitvec tests */
+ sqlite3BitvecSet(null, (u32)1);
+ sqlite3BitvecClear(null, 1, pTmpSpace);
+
+ /* Run the program */
+ pc = 0;
+ while ((op = aOp[pc]) != 0) {
+ switch (op) {
+ case 1:
+ case 2:
+ case 5: {
+ nx = 4;
+ i = aOp[pc + 2] - 1;
+ aOp[pc + 2] += aOp[pc + 3];
+ break;
+ }
+ case 3:
+ case 4:
+ default: {
+ nx = 2;
+ i64 i64Temp = 0;
+ sqlite3_randomness(sizeof(i64), ref i64Temp);
+ i = (int)i64Temp;
+ break;
+ }
+ }
+ if ((--aOp[pc + 1]) > 0)
+ nx = 0;
+ pc += nx;
+ i = (int)((i & 0x7fffffff) % sz);
+ if ((op & 1) != 0) {
+ SETBIT(pV, (i + 1));
+ if (op != 5) {
+ if (sqlite3BitvecSet(pBitvec, (u32)i + 1) != 0)
+ goto bitvec_end;
+ }
+ } else {
+ CLEARBIT(pV, (i + 1));
+ sqlite3BitvecClear(pBitvec, (u32)i + 1, pTmpSpace);
+ }
+ }
+
+ /* Test to make sure the linear array exactly matches the
+ ** Bitvec object. Start with the assumption that they do
+ ** match (rc==0). Change rc to non-zero if a discrepancy
+ ** is found.
+ */
+ rc = sqlite3BitvecTest(null, 0) + sqlite3BitvecTest(pBitvec, sz + 1)
+ + sqlite3BitvecTest(pBitvec, 0)
+ + (int)(sqlite3BitvecSize(pBitvec) - sz);
+ for (i = 1; i <= sz; i++) {
+ if ((TESTBIT(pV, i)) != sqlite3BitvecTest(pBitvec, (u32)i)) {
+ rc = i;
+ break;
+ }
+ }
+
+ /* Free allocated structure */
+ bitvec_end:
+ //sqlite3_free( ref pTmpSpace );
+ //sqlite3_free( ref pV );
+ sqlite3BitvecDestroy(ref pBitvec);
+ return rc;
}
- }
- if ( ( --aOp[pc + 1] ) > 0 )
- nx = 0;
- pc += nx;
- i = (int)( ( i & 0x7fffffff ) % sz );
- if ( ( op & 1 ) != 0 )
- {
- SETBIT( pV, ( i + 1 ) );
- if ( op != 5 )
- {
- if ( sqlite3BitvecSet( pBitvec, (u32)i + 1 ) != 0 )
- goto bitvec_end;
- }
- }
- else
- {
- CLEARBIT( pV, ( i + 1 ) );
- sqlite3BitvecClear( pBitvec, (u32)i + 1, pTmpSpace );
- }
- }
-
- /* Test to make sure the linear array exactly matches the
- ** Bitvec object. Start with the assumption that they do
- ** match (rc==0). Change rc to non-zero if a discrepancy
- ** is found.
- */
- rc = sqlite3BitvecTest( null, 0 ) + sqlite3BitvecTest( pBitvec, sz + 1 )
- + sqlite3BitvecTest( pBitvec, 0 )
- + (int)( sqlite3BitvecSize( pBitvec ) - sz );
- for ( i = 1; i <= sz; i++ )
- {
- if ( ( TESTBIT( pV, i ) ) != sqlite3BitvecTest( pBitvec, (u32)i ) )
- {
- rc = i;
- break;
- }
- }
-
- /* Free allocated structure */
-bitvec_end:
- //sqlite3_free( ref pTmpSpace );
- //sqlite3_free( ref pV );
- sqlite3BitvecDestroy( ref pBitvec );
- return rc;
-}
#endif //* SQLITE_OMIT_BUILTIN_TEST */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/btmutex_c.cs b/Src/IronPython.SQLite/c#sqlite/btmutex_c.cs
index 1f814b85a..e7b134c50 100644
--- a/Src/IronPython.SQLite/c#sqlite/btmutex_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/btmutex_c.cs
@@ -1,34 +1,30 @@
-using System.Diagnostics;
-
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
-/*
-** 2007 August 27
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-*************************************************************************
-**
-** This file contains code used to implement mutexes on Btree objects.
-** This code really belongs in btree.c. But btree.c is getting too
-** big and we want to break it down some. This packaged seemed like
-** a good breakout.
- *************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
-**
-*************************************************************************
-*/
-//#include "btreeInt.h"
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2007 August 27
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ **
+ ** This file contains code used to implement mutexes on Btree objects.
+ ** This code really belongs in btree.c. But btree.c is getting too
+ ** big and we want to break it down some. This packaged seemed like
+ ** a good breakout.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
+ **
+ *************************************************************************
+ */
+ //#include "btreeInt.h"
#if !SQLITE_OMIT_SHARED_CACHE
#if SQLITE_THREADSAFE
@@ -299,5 +295,5 @@ void sqlite3BtreeEnterAll(sqlite3 db){
#endif //* if SQLITE_THREADSAFE */
#endif //* ifndef SQLITE_OMIT_SHARED_CACHE */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/btree_c.cs b/Src/IronPython.SQLite/c#sqlite/btree_c.cs
index 611dcc5f1..273d6df86 100644
--- a/Src/IronPython.SQLite/c#sqlite/btree_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/btree_c.cs
@@ -3,56 +3,54 @@
using System.Text;
using i64 = System.Int64;
-using u8 = System.Byte;
+using Pgno = System.UInt32;
+using sqlite3_int64 = System.Int64;
using u16 = System.UInt16;
using u32 = System.UInt32;
using u64 = System.UInt64;
-using sqlite3_int64 = System.Int64;
-using Pgno = System.UInt32;
+using u8 = System.Byte;
-namespace Community.CsharpSqlite
-{
- using DbPage = Sqlite3.PgHdr;
+namespace Community.CsharpSqlite {
+ using DbPage = Sqlite3.PgHdr;
- public partial class Sqlite3
- {
-/*
-** 2004 April 6
-**
-** The author disclaims copyright to this source code. In place of
-** a legal notice, here is a blessing:
-**
-** May you do good and not evil.
-** May you find forgiveness for yourself and forgive others.
-** May you share freely, never taking more than you give.
-**
-** This file implements a external (disk-based) database using BTrees.
-** See the header comment on "btreeInt.h" for additional information.
-** Including a description of file format and an overview of operation.
-*************************************************************************
-** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
-** C#-SQLite is an independent reimplementation of the SQLite software library
-**
-** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
-**
-*************************************************************************
-*/
-//#include "btreeInt.h"
+ public partial class Sqlite3 {
+ /*
+ ** 2004 April 6
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ ** This file implements a external (disk-based) database using BTrees.
+ ** See the header comment on "btreeInt.h" for additional information.
+ ** Including a description of file format and an overview of operation.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "btreeInt.h"
-/*
-** The header string that appears at the beginning of every
-** SQLite database.
-*/
-static byte[] zMagicHeader = Encoding.UTF8.GetBytes( SQLITE_FILE_HEADER );
+ /*
+ ** The header string that appears at the beginning of every
+ ** SQLite database.
+ */
+ static byte[] zMagicHeader = Encoding.UTF8.GetBytes(SQLITE_FILE_HEADER);
-/*
-** Set this global variable to 1 to enable tracing using the TRACE
-** macro.
-*/
-#if TRACE
-static bool sqlite3BtreeTrace=false; /* True to enable tracing */
-//# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
-static void TRACE(string X, params object[] ap) { if (sqlite3BtreeTrace) printf(X, ap); }
+ /*
+ ** Set this global variable to 1 to enable tracing using the TRACE
+ ** macro.
+ */
+#if TRACE
+ static bool sqlite3BtreeTrace = false; /* True to enable tracing */
+ //# define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
+ static void TRACE(string X, params object[] ap) { if (sqlite3BtreeTrace) printf(X, ap); }
#else
//# define TRACE(X)
static void TRACE( string X, params object[] ap )
@@ -62,20 +60,19 @@ static void TRACE( string X, params object[] ap )
-/*
-** Extract a 2-byte big-endian integer from an array of unsigned bytes.
-** But if the value is zero, make it 65536.
-**
-** This routine is used to extract the "offset to cell content area" value
-** from the header of a btree page. If the page size is 65536 and the page
-** is empty, the offset should be 65536, but the 2-byte value stores zero.
-** This routine makes the necessary adjustment to 65536.
-*/
-//#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
-static int get2byteNotZero( byte[] X, int offset )
-{
- return ( ( ( ( (int)get2byte( X, offset ) ) - 1 ) & 0xffff ) + 1 );
-}
+ /*
+ ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
+ ** But if the value is zero, make it 65536.
+ **
+ ** This routine is used to extract the "offset to cell content area" value
+ ** from the header of a btree page. If the page size is 65536 and the page
+ ** is empty, the offset should be 65536, but the 2-byte value stores zero.
+ ** This routine makes the necessary adjustment to 65536.
+ */
+ //#define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
+ static int get2byteNotZero(byte[] X, int offset) {
+ return (((((int)get2byte(X, offset)) - 1) & 0xffff) + 1);
+ }
#if !SQLITE_OMIT_SHARED_CACHE
/*
@@ -110,40 +107,35 @@ int sqlite3_enable_shared_cache(int enable){
#if SQLITE_OMIT_SHARED_CACHE
-/*
-** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
-** and clearAllSharedCacheTableLocks()
-** manipulate entries in the BtShared.pLock linked list used to store
-** shared-cache table level locks. If the library is compiled with the
-** shared-cache feature disabled, then there is only ever one user
-** of each BtShared structure and so this locking is not necessary.
-** So define the lock related functions as no-ops.
-*/
-//#define querySharedCacheTableLock(a,b,c) SQLITE_OK
-static int querySharedCacheTableLock( Btree p, Pgno iTab, u8 eLock )
-{
- return SQLITE_OK;
-}
+ /*
+ ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
+ ** and clearAllSharedCacheTableLocks()
+ ** manipulate entries in the BtShared.pLock linked list used to store
+ ** shared-cache table level locks. If the library is compiled with the
+ ** shared-cache feature disabled, then there is only ever one user
+ ** of each BtShared structure and so this locking is not necessary.
+ ** So define the lock related functions as no-ops.
+ */
+ //#define querySharedCacheTableLock(a,b,c) SQLITE_OK
+ static int querySharedCacheTableLock(Btree p, Pgno iTab, u8 eLock) {
+ return SQLITE_OK;
+ }
-//#define setSharedCacheTableLock(a,b,c) SQLITE_OK
-//#define clearAllSharedCacheTableLocks(a)
-static void clearAllSharedCacheTableLocks( Btree a )
-{
-}
-//#define downgradeAllSharedCacheTableLocks(a)
-static void downgradeAllSharedCacheTableLocks( Btree a )
-{
-}
-//#define hasSharedCacheTableLock(a,b,c,d) 1
-static bool hasSharedCacheTableLock( Btree a, Pgno b, int c, int d )
-{
- return true;
-}
-//#define hasReadConflicts(a, b) 0
-static bool hasReadConflicts( Btree a, Pgno b )
-{
- return false;
-}
+ //#define setSharedCacheTableLock(a,b,c) SQLITE_OK
+ //#define clearAllSharedCacheTableLocks(a)
+ static void clearAllSharedCacheTableLocks(Btree a) {
+ }
+ //#define downgradeAllSharedCacheTableLocks(a)
+ static void downgradeAllSharedCacheTableLocks(Btree a) {
+ }
+ //#define hasSharedCacheTableLock(a,b,c,d) 1
+ static bool hasSharedCacheTableLock(Btree a, Pgno b, int c, int d) {
+ return true;
+ }
+ //#define hasReadConflicts(a, b) 0
+ static bool hasReadConflicts(Btree a, Pgno b) {
+ return false;
+ }
#endif
#if !SQLITE_OMIT_SHARED_CACHE
@@ -470,18 +462,17 @@ static void downgradeAllSharedCacheTableLocks(Btree p){
#endif //* SQLITE_OMIT_SHARED_CACHE */
-//static void releasePage(MemPage pPage); /* Forward reference */
+ //static void releasePage(MemPage pPage); /* Forward reference */
-/*
-***** This routine is used inside of assert() only ****
-**
-** Verify that the cursor holds the mutex on its BtShared
-*/
+ /*
+ ***** This routine is used inside of assert() only ****
+ **
+ ** Verify that the cursor holds the mutex on its BtShared
+ */
#if SQLITE_DEBUG
-static bool cursorHoldsMutex( BtCursor p )
-{
- return sqlite3_mutex_held( p.pBt.mutex );
-}
+ static bool cursorHoldsMutex(BtCursor p) {
+ return sqlite3_mutex_held(p.pBt.mutex);
+ }
#else
static bool cursorHoldsMutex(BtCursor p) { return true; }
#endif
@@ -538,430 +529,387 @@ static void invalidateIncrblobCursors(
}
#else
-/* Stub functions when INCRBLOB is omitted */
-//#define invalidateOverflowCache(x)
-static void invalidateOverflowCache( BtCursor pCur )
-{
-}
-//#define invalidateAllOverflowCache(x)
-static void invalidateAllOverflowCache( BtShared pBt )
-{
-}
-//#define invalidateIncrblobCursors(x,y,z)
-static void invalidateIncrblobCursors( Btree x, i64 y, int z )
-{
-}
+ /* Stub functions when INCRBLOB is omitted */
+ //#define invalidateOverflowCache(x)
+ static void invalidateOverflowCache(BtCursor pCur) {
+ }
+ //#define invalidateAllOverflowCache(x)
+ static void invalidateAllOverflowCache(BtShared pBt) {
+ }
+ //#define invalidateIncrblobCursors(x,y,z)
+ static void invalidateIncrblobCursors(Btree x, i64 y, int z) {
+ }
#endif //* SQLITE_OMIT_INCRBLOB */
-/*
-** Set bit pgno of the BtShared.pHasContent bitvec. This is called
-** when a page that previously contained data becomes a free-list leaf
-** page.
-**
-** The BtShared.pHasContent bitvec exists to work around an obscure
-** bug caused by the interaction of two useful IO optimizations surrounding
-** free-list leaf pages:
-**
-** 1) When all data is deleted from a page and the page becomes
-** a free-list leaf page, the page is not written to the database
-** (as free-list leaf pages contain no meaningful data). Sometimes
-** such a page is not even journalled (as it will not be modified,
-** why bother journalling it?).
-**
-** 2) When a free-list leaf page is reused, its content is not read
-** from the database or written to the journal file (why should it
-** be, if it is not at all meaningful?).
-**
-** By themselves, these optimizations work fine and provide a handy
-** performance boost to bulk delete or insert operations. However, if
-** a page is moved to the free-list and then reused within the same
-** transaction, a problem comes up. If the page is not journalled when
-** it is moved to the free-list and it is also not journalled when it
-** is extracted from the free-list and reused, then the original data
-** may be lost. In the event of a rollback, it may not be possible
-** to restore the database to its original configuration.
-**
-** The solution is the BtShared.pHasContent bitvec. Whenever a page is
-** moved to become a free-list leaf page, the corresponding bit is
-** set in the bitvec. Whenever a leaf page is extracted from the free-list,
-** optimization 2 above is omitted if the corresponding bit is already
-** set in BtShared.pHasContent. The contents of the bitvec are cleared
-** at the end of every transaction.
-*/
-static int btreeSetHasContent( BtShared pBt, Pgno pgno )
-{
- int rc = SQLITE_OK;
- if ( null == pBt.pHasContent )
- {
- Debug.Assert( pgno <= pBt.nPage );
- pBt.pHasContent = sqlite3BitvecCreate( pBt.nPage );
- //if ( null == pBt.pHasContent )
- //{
- // rc = SQLITE_NOMEM;
- //}
- }
- if ( rc == SQLITE_OK && pgno <= sqlite3BitvecSize( pBt.pHasContent ) )
- {
- rc = sqlite3BitvecSet( pBt.pHasContent, pgno );
- }
- return rc;
-}
+ /*
+ ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
+ ** when a page that previously contained data becomes a free-list leaf
+ ** page.
+ **
+ ** The BtShared.pHasContent bitvec exists to work around an obscure
+ ** bug caused by the interaction of two useful IO optimizations surrounding
+ ** free-list leaf pages:
+ **
+ ** 1) When all data is deleted from a page and the page becomes
+ ** a free-list leaf page, the page is not written to the database
+ ** (as free-list leaf pages contain no meaningful data). Sometimes
+ ** such a page is not even journalled (as it will not be modified,
+ ** why bother journalling it?).
+ **
+ ** 2) When a free-list leaf page is reused, its content is not read
+ ** from the database or written to the journal file (why should it
+ ** be, if it is not at all meaningful?).
+ **
+ ** By themselves, these optimizations work fine and provide a handy
+ ** performance boost to bulk delete or insert operations. However, if
+ ** a page is moved to the free-list and then reused within the same
+ ** transaction, a problem comes up. If the page is not journalled when
+ ** it is moved to the free-list and it is also not journalled when it
+ ** is extracted from the free-list and reused, then the original data
+ ** may be lost. In the event of a rollback, it may not be possible
+ ** to restore the database to its original configuration.
+ **
+ ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
+ ** moved to become a free-list leaf page, the corresponding bit is
+ ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
+ ** optimization 2 above is omitted if the corresponding bit is already
+ ** set in BtShared.pHasContent. The contents of the bitvec are cleared
+ ** at the end of every transaction.
+ */
+ static int btreeSetHasContent(BtShared pBt, Pgno pgno) {
+ int rc = SQLITE_OK;
+ if (null == pBt.pHasContent) {
+ Debug.Assert(pgno <= pBt.nPage);
+ pBt.pHasContent = sqlite3BitvecCreate(pBt.nPage);
+ //if ( null == pBt.pHasContent )
+ //{
+ // rc = SQLITE_NOMEM;
+ //}
+ }
+ if (rc == SQLITE_OK && pgno <= sqlite3BitvecSize(pBt.pHasContent)) {
+ rc = sqlite3BitvecSet(pBt.pHasContent, pgno);
+ }
+ return rc;
+ }
-/*
-** Query the BtShared.pHasContent vector.
-**
-** This function is called when a free-list leaf page is removed from the
-** free-list for reuse. It returns false if it is safe to retrieve the
-** page from the pager layer with the 'no-content' flag set. True otherwise.
-*/
-static bool btreeGetHasContent( BtShared pBt, Pgno pgno )
-{
- Bitvec p = pBt.pHasContent;
- return ( p != null && ( pgno > sqlite3BitvecSize( p ) || sqlite3BitvecTest( p, pgno ) != 0 ) );
-}
+ /*
+ ** Query the BtShared.pHasContent vector.
+ **
+ ** This function is called when a free-list leaf page is removed from the
+ ** free-list for reuse. It returns false if it is safe to retrieve the
+ ** page from the pager layer with the 'no-content' flag set. True otherwise.
+ */
+ static bool btreeGetHasContent(BtShared pBt, Pgno pgno) {
+ Bitvec p = pBt.pHasContent;
+ return (p != null && (pgno > sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno) != 0));
+ }
-/*
-** Clear (destroy) the BtShared.pHasContent bitvec. This should be
-** invoked at the conclusion of each write-transaction.
-*/
-static void btreeClearHasContent( BtShared pBt )
-{
- sqlite3BitvecDestroy( ref pBt.pHasContent );
- pBt.pHasContent = null;
-}
+ /*
+ ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
+ ** invoked at the conclusion of each write-transaction.
+ */
+ static void btreeClearHasContent(BtShared pBt) {
+ sqlite3BitvecDestroy(ref pBt.pHasContent);
+ pBt.pHasContent = null;
+ }
-/*
-** Save the current cursor position in the variables BtCursor.nKey
-** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
-**
-** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
-** prior to calling this routine.
-*/
-static int saveCursorPosition( BtCursor pCur )
-{
- int rc;
-
- Debug.Assert( CURSOR_VALID == pCur.eState );
- Debug.Assert( null == pCur.pKey );
- Debug.Assert( cursorHoldsMutex( pCur ) );
-
- rc = sqlite3BtreeKeySize( pCur, ref pCur.nKey );
- Debug.Assert( rc == SQLITE_OK ); /* KeySize() cannot fail */
-
- /* If this is an intKey table, then the above call to BtreeKeySize()
- ** stores the integer key in pCur.nKey. In this case this value is
- ** all that is required. Otherwise, if pCur is not open on an intKey
- ** table, then malloc space for and store the pCur.nKey bytes of key
- ** data.
- */
- if ( 0 == pCur.apPage[0].intKey )
- {
- byte[] pKey = sqlite3Malloc( (int)pCur.nKey );
- //if( pKey !=null){
- rc = sqlite3BtreeKey( pCur, 0, (u32)pCur.nKey, pKey );
- if ( rc == SQLITE_OK )
- {
- pCur.pKey = pKey;
- }
- //else{
- // sqlite3_free(ref pKey);
- //}
- //}else{
- // rc = SQLITE_NOMEM;
- //}
- }
- Debug.Assert( 0 == pCur.apPage[0].intKey || null == pCur.pKey );
-
- if ( rc == SQLITE_OK )
- {
- int i;
- for ( i = 0; i <= pCur.iPage; i++ )
- {
- releasePage( pCur.apPage[i] );
- pCur.apPage[i] = null;
- }
- pCur.iPage = -1;
- pCur.eState = CURSOR_REQUIRESEEK;
- }
+ /*
+ ** Save the current cursor position in the variables BtCursor.nKey
+ ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
+ **
+ ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
+ ** prior to calling this routine.
+ */
+ static int saveCursorPosition(BtCursor pCur) {
+ int rc;
+
+ Debug.Assert(CURSOR_VALID == pCur.eState);
+ Debug.Assert(null == pCur.pKey);
+ Debug.Assert(cursorHoldsMutex(pCur));
+
+ rc = sqlite3BtreeKeySize(pCur, ref pCur.nKey);
+ Debug.Assert(rc == SQLITE_OK); /* KeySize() cannot fail */
+
+ /* If this is an intKey table, then the above call to BtreeKeySize()
+ ** stores the integer key in pCur.nKey. In this case this value is
+ ** all that is required. Otherwise, if pCur is not open on an intKey
+ ** table, then malloc space for and store the pCur.nKey bytes of key
+ ** data.
+ */
+ if (0 == pCur.apPage[0].intKey) {
+ byte[] pKey = sqlite3Malloc((int)pCur.nKey);
+ //if( pKey !=null){
+ rc = sqlite3BtreeKey(pCur, 0, (u32)pCur.nKey, pKey);
+ if (rc == SQLITE_OK) {
+ pCur.pKey = pKey;
+ }
+ //else{
+ // sqlite3_free(ref pKey);
+ //}
+ //}else{
+ // rc = SQLITE_NOMEM;
+ //}
+ }
+ Debug.Assert(0 == pCur.apPage[0].intKey || null == pCur.pKey);
+
+ if (rc == SQLITE_OK) {
+ int i;
+ for (i = 0; i <= pCur.iPage; i++) {
+ releasePage(pCur.apPage[i]);
+ pCur.apPage[i] = null;
+ }
+ pCur.iPage = -1;
+ pCur.eState = CURSOR_REQUIRESEEK;
+ }
- invalidateOverflowCache( pCur );
- return rc;
-}
+ invalidateOverflowCache(pCur);
+ return rc;
+ }
-/*
-** Save the positions of all cursors (except pExcept) that are open on
-** the table with root-page iRoot. Usually, this is called just before cursor
-** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
-*/
-static int saveAllCursors( BtShared pBt, Pgno iRoot, BtCursor pExcept )
-{
- BtCursor p;
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( pExcept == null || pExcept.pBt == pBt );
- for ( p = pBt.pCursor; p != null; p = p.pNext )
- {
- if ( p != pExcept && ( 0 == iRoot || p.pgnoRoot == iRoot ) &&
- p.eState == CURSOR_VALID )
- {
- int rc = saveCursorPosition( p );
- if ( SQLITE_OK != rc )
- {
- return rc;
- }
- }
- }
- return SQLITE_OK;
-}
+ /*
+ ** Save the positions of all cursors (except pExcept) that are open on
+ ** the table with root-page iRoot. Usually, this is called just before cursor
+ ** pExcept is used to modify the table (BtreeDelete() or BtreeInsert()).
+ */
+ static int saveAllCursors(BtShared pBt, Pgno iRoot, BtCursor pExcept) {
+ BtCursor p;
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(pExcept == null || pExcept.pBt == pBt);
+ for (p = pBt.pCursor; p != null; p = p.pNext) {
+ if (p != pExcept && (0 == iRoot || p.pgnoRoot == iRoot) &&
+ p.eState == CURSOR_VALID) {
+ int rc = saveCursorPosition(p);
+ if (SQLITE_OK != rc) {
+ return rc;
+ }
+ }
+ }
+ return SQLITE_OK;
+ }
-/*
-** Clear the current cursor position.
-*/
-static void sqlite3BtreeClearCursor( BtCursor pCur )
-{
- Debug.Assert( cursorHoldsMutex( pCur ) );
- sqlite3_free( ref pCur.pKey );
- pCur.eState = CURSOR_INVALID;
-}
+ /*
+ ** Clear the current cursor position.
+ */
+ static void sqlite3BtreeClearCursor(BtCursor pCur) {
+ Debug.Assert(cursorHoldsMutex(pCur));
+ sqlite3_free(ref pCur.pKey);
+ pCur.eState = CURSOR_INVALID;
+ }
-/*
-** In this version of BtreeMoveto, pKey is a packed index record
-** such as is generated by the OP_MakeRecord opcode. Unpack the
-** record and then call BtreeMovetoUnpacked() to do the work.
-*/
-static int btreeMoveto(
-BtCursor pCur, /* Cursor open on the btree to be searched */
-byte[] pKey, /* Packed key if the btree is an index */
-i64 nKey, /* Integer key for tables. Size of pKey for indices */
-int bias, /* Bias search to the high end */
-ref int pRes /* Write search results here */
-)
-{
- int rc; /* Status code */
- UnpackedRecord pIdxKey; /* Unpacked index key */
- UnpackedRecord aSpace = new UnpackedRecord();//char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
-
- if ( pKey != null )
- {
- Debug.Assert( nKey == (i64)(int)nKey );
- pIdxKey = sqlite3VdbeRecordUnpack( pCur.pKeyInfo, (int)nKey, pKey,
- aSpace, 16 );//sizeof( aSpace ) );
- //if ( pIdxKey == null )
- // return SQLITE_NOMEM;
- }
- else
- {
- pIdxKey = null;
- }
- rc = sqlite3BtreeMovetoUnpacked( pCur, pIdxKey, nKey, bias != 0 ? 1 : 0, ref pRes );
-
- if ( pKey != null )
- {
- sqlite3VdbeDeleteUnpackedRecord( pIdxKey );
- }
- return rc;
-}
+ /*
+ ** In this version of BtreeMoveto, pKey is a packed index record
+ ** such as is generated by the OP_MakeRecord opcode. Unpack the
+ ** record and then call BtreeMovetoUnpacked() to do the work.
+ */
+ static int btreeMoveto(
+ BtCursor pCur, /* Cursor open on the btree to be searched */
+ byte[] pKey, /* Packed key if the btree is an index */
+ i64 nKey, /* Integer key for tables. Size of pKey for indices */
+ int bias, /* Bias search to the high end */
+ ref int pRes /* Write search results here */
+ ) {
+ int rc; /* Status code */
+ UnpackedRecord pIdxKey; /* Unpacked index key */
+ UnpackedRecord aSpace = new UnpackedRecord();//char aSpace[150]; /* Temp space for pIdxKey - to avoid a malloc */
+
+ if (pKey != null) {
+ Debug.Assert(nKey == (i64)(int)nKey);
+ pIdxKey = sqlite3VdbeRecordUnpack(pCur.pKeyInfo, (int)nKey, pKey,
+ aSpace, 16);//sizeof( aSpace ) );
+ //if ( pIdxKey == null )
+ // return SQLITE_NOMEM;
+ } else {
+ pIdxKey = null;
+ }
+ rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias != 0 ? 1 : 0, ref pRes);
-/*
-** Restore the cursor to the position it was in (or as close to as possible)
-** when saveCursorPosition() was called. Note that this call deletes the
-** saved position info stored by saveCursorPosition(), so there can be
-** at most one effective restoreCursorPosition() call after each
-** saveCursorPosition().
-*/
-static int btreeRestoreCursorPosition( BtCursor pCur )
-{
- int rc;
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState >= CURSOR_REQUIRESEEK );
- if ( pCur.eState == CURSOR_FAULT )
- {
- return pCur.skipNext;
- }
- pCur.eState = CURSOR_INVALID;
- rc = btreeMoveto( pCur, pCur.pKey, pCur.nKey, 0, ref pCur.skipNext );
- if ( rc == SQLITE_OK )
- {
- //sqlite3_free(ref pCur.pKey);
- pCur.pKey = null;
- Debug.Assert( pCur.eState == CURSOR_VALID || pCur.eState == CURSOR_INVALID );
- }
- return rc;
-}
+ if (pKey != null) {
+ sqlite3VdbeDeleteUnpackedRecord(pIdxKey);
+ }
+ return rc;
+ }
-//#define restoreCursorPosition(p) \
-// (p.eState>=CURSOR_REQUIRESEEK ? \
-// btreeRestoreCursorPosition(p) : \
-// SQLITE_OK)
-static int restoreCursorPosition( BtCursor pCur )
-{
- if ( pCur.eState >= CURSOR_REQUIRESEEK )
- return btreeRestoreCursorPosition( pCur );
- else
- return SQLITE_OK;
-}
+ /*
+ ** Restore the cursor to the position it was in (or as close to as possible)
+ ** when saveCursorPosition() was called. Note that this call deletes the
+ ** saved position info stored by saveCursorPosition(), so there can be
+ ** at most one effective restoreCursorPosition() call after each
+ ** saveCursorPosition().
+ */
+ static int btreeRestoreCursorPosition(BtCursor pCur) {
+ int rc;
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState >= CURSOR_REQUIRESEEK);
+ if (pCur.eState == CURSOR_FAULT) {
+ return pCur.skipNext;
+ }
+ pCur.eState = CURSOR_INVALID;
+ rc = btreeMoveto(pCur, pCur.pKey, pCur.nKey, 0, ref pCur.skipNext);
+ if (rc == SQLITE_OK) {
+ //sqlite3_free(ref pCur.pKey);
+ pCur.pKey = null;
+ Debug.Assert(pCur.eState == CURSOR_VALID || pCur.eState == CURSOR_INVALID);
+ }
+ return rc;
+ }
-/*
-** Determine whether or not a cursor has moved from the position it
-** was last placed at. Cursors can move when the row they are pointing
-** at is deleted out from under them.
-**
-** This routine returns an error code if something goes wrong. The
-** integer pHasMoved is set to one if the cursor has moved and 0 if not.
-*/
-static int sqlite3BtreeCursorHasMoved( BtCursor pCur, ref int pHasMoved )
-{
- int rc;
-
- rc = restoreCursorPosition( pCur );
- if ( rc != 0 )
- {
- pHasMoved = 1;
- return rc;
- }
- if ( pCur.eState != CURSOR_VALID || pCur.skipNext != 0 )
- {
- pHasMoved = 1;
- }
- else
- {
- pHasMoved = 0;
- }
- return SQLITE_OK;
-}
+ //#define restoreCursorPosition(p) \
+ // (p.eState>=CURSOR_REQUIRESEEK ? \
+ // btreeRestoreCursorPosition(p) : \
+ // SQLITE_OK)
+ static int restoreCursorPosition(BtCursor pCur) {
+ if (pCur.eState >= CURSOR_REQUIRESEEK)
+ return btreeRestoreCursorPosition(pCur);
+ else
+ return SQLITE_OK;
+ }
+
+ /*
+ ** Determine whether or not a cursor has moved from the position it
+ ** was last placed at. Cursors can move when the row they are pointing
+ ** at is deleted out from under them.
+ **
+ ** This routine returns an error code if something goes wrong. The
+ ** integer pHasMoved is set to one if the cursor has moved and 0 if not.
+ */
+ static int sqlite3BtreeCursorHasMoved(BtCursor pCur, ref int pHasMoved) {
+ int rc;
+
+ rc = restoreCursorPosition(pCur);
+ if (rc != 0) {
+ pHasMoved = 1;
+ return rc;
+ }
+ if (pCur.eState != CURSOR_VALID || pCur.skipNext != 0) {
+ pHasMoved = 1;
+ } else {
+ pHasMoved = 0;
+ }
+ return SQLITE_OK;
+ }
#if !SQLITE_OMIT_AUTOVACUUM
-/*
-** Given a page number of a regular database page, return the page
-** number for the pointer-map page that contains the entry for the
-** input page number.
-**
-** Return 0 (not a valid page) for pgno==1 since there is
-** no pointer map associated with page 1. The integrity_check logic
-** requires that ptrmapPageno(*,1)!=1.
-*/
-static Pgno ptrmapPageno( BtShared pBt, Pgno pgno )
-{
- int nPagesPerMapPage;
- Pgno iPtrMap, ret;
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- if ( pgno < 2 )
- return 0;
- nPagesPerMapPage = (int)( pBt.usableSize / 5 + 1 );
- iPtrMap = (Pgno)( ( pgno - 2 ) / nPagesPerMapPage );
- ret = (Pgno)( iPtrMap * nPagesPerMapPage ) + 2;
- if ( ret == PENDING_BYTE_PAGE( pBt ) )
- {
- ret++;
- }
- return ret;
-}
+ /*
+ ** Given a page number of a regular database page, return the page
+ ** number for the pointer-map page that contains the entry for the
+ ** input page number.
+ **
+ ** Return 0 (not a valid page) for pgno==1 since there is
+ ** no pointer map associated with page 1. The integrity_check logic
+ ** requires that ptrmapPageno(*,1)!=1.
+ */
+ static Pgno ptrmapPageno(BtShared pBt, Pgno pgno) {
+ int nPagesPerMapPage;
+ Pgno iPtrMap, ret;
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ if (pgno < 2)
+ return 0;
+ nPagesPerMapPage = (int)(pBt.usableSize / 5 + 1);
+ iPtrMap = (Pgno)((pgno - 2) / nPagesPerMapPage);
+ ret = (Pgno)(iPtrMap * nPagesPerMapPage) + 2;
+ if (ret == PENDING_BYTE_PAGE(pBt)) {
+ ret++;
+ }
+ return ret;
+ }
-/*
-** Write an entry into the pointer map.
-**
-** This routine updates the pointer map entry for page number 'key'
-** so that it maps to type 'eType' and parent page number 'pgno'.
-**
-** If pRC is initially non-zero (non-SQLITE_OK) then this routine is
-** a no-op. If an error occurs, the appropriate error code is written
-** into pRC.
-*/
-static void ptrmapPut( BtShared pBt, Pgno key, u8 eType, Pgno parent, ref int pRC )
-{
- PgHdr pDbPage = new PgHdr(); /* The pointer map page */
- u8[] pPtrmap; /* The pointer map data */
- Pgno iPtrmap; /* The pointer map page number */
- int offset; /* Offset in pointer map page */
- int rc; /* Return code from subfunctions */
-
- if ( pRC != 0 )
- return;
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- /* The master-journal page number must never be used as a pointer map page */
- Debug.Assert( false == PTRMAP_ISPAGE( pBt, PENDING_BYTE_PAGE( pBt ) ) );
-
- Debug.Assert( pBt.autoVacuum );
- if ( key == 0 )
- {
- pRC = SQLITE_CORRUPT_BKPT();
- return;
- }
- iPtrmap = PTRMAP_PAGENO( pBt, key );
- rc = sqlite3PagerGet( pBt.pPager, iPtrmap, ref pDbPage );
- if ( rc != SQLITE_OK )
- {
- pRC = rc;
- return;
- }
- offset = (int)PTRMAP_PTROFFSET( iPtrmap, key );
- if ( offset < 0 )
- {
- pRC = SQLITE_CORRUPT_BKPT();
- goto ptrmap_exit;
- }
- Debug.Assert( offset <= (int)pBt.usableSize - 5 );
- pPtrmap = sqlite3PagerGetData( pDbPage );
-
- if ( eType != pPtrmap[offset] || sqlite3Get4byte( pPtrmap, offset + 1 ) != parent )
- {
- TRACE( "PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent );
- pRC = rc = sqlite3PagerWrite( pDbPage );
- if ( rc == SQLITE_OK )
- {
- pPtrmap[offset] = eType;
- sqlite3Put4byte( pPtrmap, offset + 1, parent );
- }
- }
+ /*
+ ** Write an entry into the pointer map.
+ **
+ ** This routine updates the pointer map entry for page number 'key'
+ ** so that it maps to type 'eType' and parent page number 'pgno'.
+ **
+ ** If pRC is initially non-zero (non-SQLITE_OK) then this routine is
+ ** a no-op. If an error occurs, the appropriate error code is written
+ ** into pRC.
+ */
+ static void ptrmapPut(BtShared pBt, Pgno key, u8 eType, Pgno parent, ref int pRC) {
+ PgHdr pDbPage = new PgHdr(); /* The pointer map page */
+ u8[] pPtrmap; /* The pointer map data */
+ Pgno iPtrmap; /* The pointer map page number */
+ int offset; /* Offset in pointer map page */
+ int rc; /* Return code from subfunctions */
+
+ if (pRC != 0)
+ return;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ /* The master-journal page number must never be used as a pointer map page */
+ Debug.Assert(false == PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)));
+
+ Debug.Assert(pBt.autoVacuum);
+ if (key == 0) {
+ pRC = SQLITE_CORRUPT_BKPT();
+ return;
+ }
+ iPtrmap = PTRMAP_PAGENO(pBt, key);
+ rc = sqlite3PagerGet(pBt.pPager, iPtrmap, ref pDbPage);
+ if (rc != SQLITE_OK) {
+ pRC = rc;
+ return;
+ }
+ offset = (int)PTRMAP_PTROFFSET(iPtrmap, key);
+ if (offset < 0) {
+ pRC = SQLITE_CORRUPT_BKPT();
+ goto ptrmap_exit;
+ }
+ Debug.Assert(offset <= (int)pBt.usableSize - 5);
+ pPtrmap = sqlite3PagerGetData(pDbPage);
+
+ if (eType != pPtrmap[offset] || sqlite3Get4byte(pPtrmap, offset + 1) != parent) {
+ TRACE("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent);
+ pRC = rc = sqlite3PagerWrite(pDbPage);
+ if (rc == SQLITE_OK) {
+ pPtrmap[offset] = eType;
+ sqlite3Put4byte(pPtrmap, offset + 1, parent);
+ }
+ }
-ptrmap_exit:
- sqlite3PagerUnref( pDbPage );
-}
+ ptrmap_exit:
+ sqlite3PagerUnref(pDbPage);
+ }
-/*
-** Read an entry from the pointer map.
-**
-** This routine retrieves the pointer map entry for page 'key', writing
-** the type and parent page number to pEType and pPgno respectively.
-** An error code is returned if something goes wrong, otherwise SQLITE_OK.
-*/
-static int ptrmapGet( BtShared pBt, Pgno key, ref u8 pEType, ref Pgno pPgno )
-{
- PgHdr pDbPage = new PgHdr();/* The pointer map page */
- int iPtrmap; /* Pointer map page index */
- u8[] pPtrmap; /* Pointer map page data */
- int offset; /* Offset of entry in pointer map */
- int rc;
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
-
- iPtrmap = (int)PTRMAP_PAGENO( pBt, key );
- rc = sqlite3PagerGet( pBt.pPager, (u32)iPtrmap, ref pDbPage );
- if ( rc != 0 )
- {
- return rc;
- }
- pPtrmap = sqlite3PagerGetData( pDbPage );
-
- offset = (int)PTRMAP_PTROFFSET( (u32)iPtrmap, key );
- if ( offset < 0 )
- {
- sqlite3PagerUnref( pDbPage );
- return SQLITE_CORRUPT_BKPT();
- }
- Debug.Assert( offset <= (int)pBt.usableSize - 5 );
- // Under C# pEType will always exist. No need to test; //
- //Debug.Assert( pEType != 0 );
- pEType = pPtrmap[offset];
- // Under C# pPgno will always exist. No need to test; //
- //if ( pPgno != 0 )
- pPgno = sqlite3Get4byte( pPtrmap, offset + 1 );
-
- sqlite3PagerUnref( pDbPage );
- if ( pEType < 1 || pEType > 5 )
- return SQLITE_CORRUPT_BKPT();
- return SQLITE_OK;
-}
+ /*
+ ** Read an entry from the pointer map.
+ **
+ ** This routine retrieves the pointer map entry for page 'key', writing
+ ** the type and parent page number to pEType and pPgno respectively.
+ ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
+ */
+ static int ptrmapGet(BtShared pBt, Pgno key, ref u8 pEType, ref Pgno pPgno) {
+ PgHdr pDbPage = new PgHdr();/* The pointer map page */
+ int iPtrmap; /* Pointer map page index */
+ u8[] pPtrmap; /* Pointer map page data */
+ int offset; /* Offset of entry in pointer map */
+ int rc;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+
+ iPtrmap = (int)PTRMAP_PAGENO(pBt, key);
+ rc = sqlite3PagerGet(pBt.pPager, (u32)iPtrmap, ref pDbPage);
+ if (rc != 0) {
+ return rc;
+ }
+ pPtrmap = sqlite3PagerGetData(pDbPage);
+
+ offset = (int)PTRMAP_PTROFFSET((u32)iPtrmap, key);
+ if (offset < 0) {
+ sqlite3PagerUnref(pDbPage);
+ return SQLITE_CORRUPT_BKPT();
+ }
+ Debug.Assert(offset <= (int)pBt.usableSize - 5);
+ // Under C# pEType will always exist. No need to test; //
+ //Debug.Assert( pEType != 0 );
+ pEType = pPtrmap[offset];
+ // Under C# pPgno will always exist. No need to test; //
+ //if ( pPgno != 0 )
+ pPgno = sqlite3Get4byte(pPtrmap, offset + 1);
+
+ sqlite3PagerUnref(pDbPage);
+ if (pEType < 1 || pEType > 5)
+ return SQLITE_CORRUPT_BKPT();
+ return SQLITE_OK;
+ }
#else //* if defined SQLITE_OMIT_AUTOVACUUM */
//#define ptrmapPut(w,x,y,z,rc)
@@ -969,374 +917,332 @@ static int ptrmapGet( BtShared pBt, Pgno key, ref u8 pEType, ref Pgno pPgno )
//#define ptrmapPutOvflPtr(x, y, rc)
#endif
-/*
-** Given a btree page and a cell index (0 means the first cell on
-** the page, 1 means the second cell, and so forth) return a pointer
-** to the cell content.
-**
-** This routine works only for pages that do not contain overflow cells.
-*/
-//#define findCell(P,I) \
-// ((P).aData + ((P).maskPage & get2byte((P).aData[(P).cellOffset+2*(I)])))
-static int findCell( MemPage pPage, int iCell )
-{
- return get2byte( pPage.aData, pPage.cellOffset + 2 * ( iCell ) );
-}
+ /*
+ ** Given a btree page and a cell index (0 means the first cell on
+ ** the page, 1 means the second cell, and so forth) return a pointer
+ ** to the cell content.
+ **
+ ** This routine works only for pages that do not contain overflow cells.
+ */
+ //#define findCell(P,I) \
+ // ((P).aData + ((P).maskPage & get2byte((P).aData[(P).cellOffset+2*(I)])))
+ static int findCell(MemPage pPage, int iCell) {
+ return get2byte(pPage.aData, pPage.cellOffset + 2 * (iCell));
+ }
-//#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
-static u8[] findCellv2( u8[] pPage, u16 iCell, u16 O, int I )
-{
- Debugger.Break();
- return pPage;
-}
+ //#define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
+ static u8[] findCellv2(u8[] pPage, u16 iCell, u16 O, int I) {
+ Debugger.Break();
+ return pPage;
+ }
-/*
-** This a more complex version of findCell() that works for
-** pages that do contain overflow cells.
-*/
-static int findOverflowCell( MemPage pPage, int iCell )
-{
- int i;
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- for ( i = pPage.nOverflow - 1; i >= 0; i-- )
- {
- int k;
- _OvflCell pOvfl;
- pOvfl = pPage.aOvfl[i];
- k = pOvfl.idx;
- if ( k <= iCell )
- {
- if ( k == iCell )
- {
- //return pOvfl.pCell;
- return -i - 1; // Negative Offset means overflow cells
- }
- iCell--;
- }
- }
- return findCell( pPage, iCell );
-}
+ /*
+ ** This a more complex version of findCell() that works for
+ ** pages that do contain overflow cells.
+ */
+ static int findOverflowCell(MemPage pPage, int iCell) {
+ int i;
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ for (i = pPage.nOverflow - 1; i >= 0; i--) {
+ int k;
+ _OvflCell pOvfl;
+ pOvfl = pPage.aOvfl[i];
+ k = pOvfl.idx;
+ if (k <= iCell) {
+ if (k == iCell) {
+ //return pOvfl.pCell;
+ return -i - 1; // Negative Offset means overflow cells
+ }
+ iCell--;
+ }
+ }
+ return findCell(pPage, iCell);
+ }
-/*
-** Parse a cell content block and fill in the CellInfo structure. There
-** are two versions of this function. btreeParseCell() takes a
-** cell index as the second argument and btreeParseCellPtr()
-** takes a pointer to the body of the cell as its second argument.
-**
-** Within this file, the parseCell() macro can be called instead of
-** btreeParseCellPtr(). Using some compilers, this will be faster.
-*/
-//OVERLOADS
-static void btreeParseCellPtr(
-MemPage pPage, /* Page containing the cell */
-int iCell, /* Pointer to the cell text. */
-ref CellInfo pInfo /* Fill in this structure */
-)
-{
- btreeParseCellPtr( pPage, pPage.aData, iCell, ref pInfo );
-}
-static void btreeParseCellPtr(
-MemPage pPage, /* Page containing the cell */
-byte[] pCell, /* The actual data */
-ref CellInfo pInfo /* Fill in this structure */
-)
-{
- btreeParseCellPtr( pPage, pCell, 0, ref pInfo );
-}
-static void btreeParseCellPtr(
-MemPage pPage, /* Page containing the cell */
-u8[] pCell, /* Pointer to the cell text. */
-int iCell, /* Pointer to the cell text. */
-ref CellInfo pInfo /* Fill in this structure */
-)
-{
- u16 n; /* Number bytes in cell content header */
- u32 nPayload = 0; /* Number of bytes of cell payload */
-
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
-
- if ( pInfo.pCell != pCell )
- pInfo.pCell = pCell;
- pInfo.iCell = iCell;
- Debug.Assert( pPage.leaf == 0 || pPage.leaf == 1 );
- n = pPage.childPtrSize;
- Debug.Assert( n == 4 - 4 * pPage.leaf );
- if ( pPage.intKey != 0 )
- {
- if ( pPage.hasData != 0 )
- {
- n += (u16)getVarint32( pCell, iCell + n, out nPayload );
- }
- else
- {
- nPayload = 0;
- }
- n += (u16)getVarint( pCell, iCell + n, out pInfo.nKey );
- pInfo.nData = nPayload;
- }
- else
- {
- pInfo.nData = 0;
- n += (u16)getVarint32( pCell, iCell + n, out nPayload );
- pInfo.nKey = nPayload;
- }
- pInfo.nPayload = nPayload;
- pInfo.nHeader = n;
- testcase( nPayload == pPage.maxLocal );
- testcase( nPayload == pPage.maxLocal + 1 );
- if ( likely( nPayload <= pPage.maxLocal ) )
- {
- /* This is the (easy) common case where the entire payload fits
- ** on the local page. No overflow is required.
- */
- if ( ( pInfo.nSize = (u16)( n + nPayload ) ) < 4 )
- pInfo.nSize = 4;
- pInfo.nLocal = (u16)nPayload;
- pInfo.iOverflow = 0;
- }
- else
- {
- /* If the payload will not fit completely on the local page, we have
- ** to decide how much to store locally and how much to spill onto
- ** overflow pages. The strategy is to minimize the amount of unused
- ** space on overflow pages while keeping the amount of local storage
- ** in between minLocal and maxLocal.
- **
- ** Warning: changing the way overflow payload is distributed in any
- ** way will result in an incompatible file format.
- */
- int minLocal; /* Minimum amount of payload held locally */
- int maxLocal; /* Maximum amount of payload held locally */
- int surplus; /* Overflow payload available for local storage */
-
- minLocal = pPage.minLocal;
- maxLocal = pPage.maxLocal;
- surplus = (int)( minLocal + ( nPayload - minLocal ) % ( pPage.pBt.usableSize - 4 ) );
- testcase( surplus == maxLocal );
- testcase( surplus == maxLocal + 1 );
- if ( surplus <= maxLocal )
- {
- pInfo.nLocal = (u16)surplus;
- }
- else
- {
- pInfo.nLocal = (u16)minLocal;
- }
- pInfo.iOverflow = (u16)( pInfo.nLocal + n );
- pInfo.nSize = (u16)( pInfo.iOverflow + 4 );
- }
-}
-//#define parseCell(pPage, iCell, pInfo) \
-// btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
-static void parseCell( MemPage pPage, int iCell, ref CellInfo pInfo )
-{
- btreeParseCellPtr( pPage, findCell( pPage, iCell ), ref pInfo );
-}
+ /*
+ ** Parse a cell content block and fill in the CellInfo structure. There
+ ** are two versions of this function. btreeParseCell() takes a
+ ** cell index as the second argument and btreeParseCellPtr()
+ ** takes a pointer to the body of the cell as its second argument.
+ **
+ ** Within this file, the parseCell() macro can be called instead of
+ ** btreeParseCellPtr(). Using some compilers, this will be faster.
+ */
+ //OVERLOADS
+ static void btreeParseCellPtr(
+ MemPage pPage, /* Page containing the cell */
+ int iCell, /* Pointer to the cell text. */
+ ref CellInfo pInfo /* Fill in this structure */
+ ) {
+ btreeParseCellPtr(pPage, pPage.aData, iCell, ref pInfo);
+ }
+ static void btreeParseCellPtr(
+ MemPage pPage, /* Page containing the cell */
+ byte[] pCell, /* The actual data */
+ ref CellInfo pInfo /* Fill in this structure */
+ ) {
+ btreeParseCellPtr(pPage, pCell, 0, ref pInfo);
+ }
+ static void btreeParseCellPtr(
+ MemPage pPage, /* Page containing the cell */
+ u8[] pCell, /* Pointer to the cell text. */
+ int iCell, /* Pointer to the cell text. */
+ ref CellInfo pInfo /* Fill in this structure */
+ ) {
+ u16 n; /* Number bytes in cell content header */
+ u32 nPayload = 0; /* Number of bytes of cell payload */
+
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+
+ if (pInfo.pCell != pCell)
+ pInfo.pCell = pCell;
+ pInfo.iCell = iCell;
+ Debug.Assert(pPage.leaf == 0 || pPage.leaf == 1);
+ n = pPage.childPtrSize;
+ Debug.Assert(n == 4 - 4 * pPage.leaf);
+ if (pPage.intKey != 0) {
+ if (pPage.hasData != 0) {
+ n += (u16)getVarint32(pCell, iCell + n, out nPayload);
+ } else {
+ nPayload = 0;
+ }
+ n += (u16)getVarint(pCell, iCell + n, out pInfo.nKey);
+ pInfo.nData = nPayload;
+ } else {
+ pInfo.nData = 0;
+ n += (u16)getVarint32(pCell, iCell + n, out nPayload);
+ pInfo.nKey = nPayload;
+ }
+ pInfo.nPayload = nPayload;
+ pInfo.nHeader = n;
+ testcase(nPayload == pPage.maxLocal);
+ testcase(nPayload == pPage.maxLocal + 1);
+ if (likely(nPayload <= pPage.maxLocal)) {
+ /* This is the (easy) common case where the entire payload fits
+ ** on the local page. No overflow is required.
+ */
+ if ((pInfo.nSize = (u16)(n + nPayload)) < 4)
+ pInfo.nSize = 4;
+ pInfo.nLocal = (u16)nPayload;
+ pInfo.iOverflow = 0;
+ } else {
+ /* If the payload will not fit completely on the local page, we have
+ ** to decide how much to store locally and how much to spill onto
+ ** overflow pages. The strategy is to minimize the amount of unused
+ ** space on overflow pages while keeping the amount of local storage
+ ** in between minLocal and maxLocal.
+ **
+ ** Warning: changing the way overflow payload is distributed in any
+ ** way will result in an incompatible file format.
+ */
+ int minLocal; /* Minimum amount of payload held locally */
+ int maxLocal; /* Maximum amount of payload held locally */
+ int surplus; /* Overflow payload available for local storage */
+
+ minLocal = pPage.minLocal;
+ maxLocal = pPage.maxLocal;
+ surplus = (int)(minLocal + (nPayload - minLocal) % (pPage.pBt.usableSize - 4));
+ testcase(surplus == maxLocal);
+ testcase(surplus == maxLocal + 1);
+ if (surplus <= maxLocal) {
+ pInfo.nLocal = (u16)surplus;
+ } else {
+ pInfo.nLocal = (u16)minLocal;
+ }
+ pInfo.iOverflow = (u16)(pInfo.nLocal + n);
+ pInfo.nSize = (u16)(pInfo.iOverflow + 4);
+ }
+ }
+ //#define parseCell(pPage, iCell, pInfo) \
+ // btreeParseCellPtr((pPage), findCell((pPage), (iCell)), (pInfo))
+ static void parseCell(MemPage pPage, int iCell, ref CellInfo pInfo) {
+ btreeParseCellPtr(pPage, findCell(pPage, iCell), ref pInfo);
+ }
-static void btreeParseCell(
-MemPage pPage, /* Page containing the cell */
-int iCell, /* The cell index. First cell is 0 */
-ref CellInfo pInfo /* Fill in this structure */
-)
-{
- parseCell( pPage, iCell, ref pInfo );
-}
+ static void btreeParseCell(
+ MemPage pPage, /* Page containing the cell */
+ int iCell, /* The cell index. First cell is 0 */
+ ref CellInfo pInfo /* Fill in this structure */
+ ) {
+ parseCell(pPage, iCell, ref pInfo);
+ }
-/*
-** Compute the total number of bytes that a Cell needs in the cell
-** data area of the btree-page. The return number includes the cell
-** data header and the local payload, but not any overflow page or
-** the space used by the cell pointer.
-*/
-// Alternative form for C#
-static u16 cellSizePtr( MemPage pPage, int iCell )
-{
- CellInfo info = new CellInfo();
- byte[] pCell = new byte[13];
- // Minimum Size = (2 bytes of Header or (4) Child Pointer) + (maximum of) 9 bytes data
- if ( iCell < 0 )// Overflow Cell
- Buffer.BlockCopy( pPage.aOvfl[-( iCell + 1 )].pCell, 0, pCell, 0, pCell.Length < pPage.aOvfl[-( iCell + 1 )].pCell.Length ? pCell.Length : pPage.aOvfl[-( iCell + 1 )].pCell.Length );
- else if ( iCell >= pPage.aData.Length + 1 - pCell.Length )
- Buffer.BlockCopy( pPage.aData, iCell, pCell, 0, pPage.aData.Length - iCell );
- else
- Buffer.BlockCopy( pPage.aData, iCell, pCell, 0, pCell.Length );
- btreeParseCellPtr( pPage, pCell, ref info );
- return info.nSize;
-}
+ /*
+ ** Compute the total number of bytes that a Cell needs in the cell
+ ** data area of the btree-page. The return number includes the cell
+ ** data header and the local payload, but not any overflow page or
+ ** the space used by the cell pointer.
+ */
+ // Alternative form for C#
+ static u16 cellSizePtr(MemPage pPage, int iCell) {
+ CellInfo info = new CellInfo();
+ byte[] pCell = new byte[13];
+ // Minimum Size = (2 bytes of Header or (4) Child Pointer) + (maximum of) 9 bytes data
+ if (iCell < 0)// Overflow Cell
+ Buffer.BlockCopy(pPage.aOvfl[-(iCell + 1)].pCell, 0, pCell, 0, pCell.Length < pPage.aOvfl[-(iCell + 1)].pCell.Length ? pCell.Length : pPage.aOvfl[-(iCell + 1)].pCell.Length);
+ else if (iCell >= pPage.aData.Length + 1 - pCell.Length)
+ Buffer.BlockCopy(pPage.aData, iCell, pCell, 0, pPage.aData.Length - iCell);
+ else
+ Buffer.BlockCopy(pPage.aData, iCell, pCell, 0, pCell.Length);
+ btreeParseCellPtr(pPage, pCell, ref info);
+ return info.nSize;
+ }
-// Alternative form for C#
-static u16 cellSizePtr( MemPage pPage, byte[] pCell, int offset )
-{
- CellInfo info = new CellInfo();
- info.pCell = sqlite3Malloc( pCell.Length );
- Buffer.BlockCopy( pCell, offset, info.pCell, 0, pCell.Length - offset );
- btreeParseCellPtr( pPage, info.pCell, ref info );
- return info.nSize;
-}
+ // Alternative form for C#
+ static u16 cellSizePtr(MemPage pPage, byte[] pCell, int offset) {
+ CellInfo info = new CellInfo();
+ info.pCell = sqlite3Malloc(pCell.Length);
+ Buffer.BlockCopy(pCell, offset, info.pCell, 0, pCell.Length - offset);
+ btreeParseCellPtr(pPage, info.pCell, ref info);
+ return info.nSize;
+ }
-static u16 cellSizePtr( MemPage pPage, u8[] pCell )
-{
- int _pIter = pPage.childPtrSize; //u8 pIter = &pCell[pPage.childPtrSize];
- u32 nSize = 0;
+ static u16 cellSizePtr(MemPage pPage, u8[] pCell) {
+ int _pIter = pPage.childPtrSize; //u8 pIter = &pCell[pPage.childPtrSize];
+ u32 nSize = 0;
#if SQLITE_DEBUG || DEBUG
- /* The value returned by this function should always be the same as
-** the (CellInfo.nSize) value found by doing a full parse of the
-** cell. If SQLITE_DEBUG is defined, an Debug.Assert() at the bottom of
-** this function verifies that this invariant is not violated. */
- CellInfo debuginfo = new CellInfo();
- btreeParseCellPtr( pPage, pCell, ref debuginfo );
+ /* The value returned by this function should always be the same as
+ ** the (CellInfo.nSize) value found by doing a full parse of the
+ ** cell. If SQLITE_DEBUG is defined, an Debug.Assert() at the bottom of
+ ** this function verifies that this invariant is not violated. */
+ CellInfo debuginfo = new CellInfo();
+ btreeParseCellPtr(pPage, pCell, ref debuginfo);
#else
CellInfo debuginfo = new CellInfo();
#endif
- if ( pPage.intKey != 0 )
- {
- int pEnd;
- if ( pPage.hasData != 0 )
- {
- _pIter += getVarint32( pCell, out nSize );// pIter += getVarint32( pIter, out nSize );
- }
- else
- {
- nSize = 0;
- }
+ if (pPage.intKey != 0) {
+ int pEnd;
+ if (pPage.hasData != 0) {
+ _pIter += getVarint32(pCell, out nSize);// pIter += getVarint32( pIter, out nSize );
+ } else {
+ nSize = 0;
+ }
+
+ /* pIter now points at the 64-bit integer key value, a variable length
+ ** integer. The following block moves pIter to point at the first byte
+ ** past the end of the key value. */
+ pEnd = _pIter + 9;//pEnd = &pIter[9];
+ while (((pCell[_pIter++]) & 0x80) != 0 && _pIter < pEnd)
+ ;//while( (pIter++)&0x80 && pIter pPage.maxLocal )
- {
- int minLocal = pPage.minLocal;
- nSize = (u32)( minLocal + ( nSize - minLocal ) % ( pPage.pBt.usableSize - 4 ) );
- testcase( nSize == pPage.maxLocal );
- testcase( nSize == pPage.maxLocal + 1 );
- if ( nSize > pPage.maxLocal )
- {
- nSize = (u32)minLocal;
- }
- nSize += 4;
- }
- nSize += (uint)_pIter;//nSize += (u32)(pIter - pCell);
-
- /* The minimum size of any cell is 4 bytes. */
- if ( nSize < 4 )
- {
- nSize = 4;
- }
-
- Debug.Assert( nSize == debuginfo.nSize );
- return (u16)nSize;
-}
+ testcase(nSize == pPage.maxLocal);
+ testcase(nSize == pPage.maxLocal + 1);
+ if (nSize > pPage.maxLocal) {
+ int minLocal = pPage.minLocal;
+ nSize = (u32)(minLocal + (nSize - minLocal) % (pPage.pBt.usableSize - 4));
+ testcase(nSize == pPage.maxLocal);
+ testcase(nSize == pPage.maxLocal + 1);
+ if (nSize > pPage.maxLocal) {
+ nSize = (u32)minLocal;
+ }
+ nSize += 4;
+ }
+ nSize += (uint)_pIter;//nSize += (u32)(pIter - pCell);
+
+ /* The minimum size of any cell is 4 bytes. */
+ if (nSize < 4) {
+ nSize = 4;
+ }
+
+ Debug.Assert(nSize == debuginfo.nSize);
+ return (u16)nSize;
+ }
#if SQLITE_DEBUG
-/* This variation on cellSizePtr() is used inside of assert() statements
-** only. */
-static u16 cellSize( MemPage pPage, int iCell )
-{
- return cellSizePtr( pPage, findCell( pPage, iCell ) );
-}
+ /* This variation on cellSizePtr() is used inside of assert() statements
+ ** only. */
+ static u16 cellSize(MemPage pPage, int iCell) {
+ return cellSizePtr(pPage, findCell(pPage, iCell));
+ }
#else
static int cellSize(MemPage pPage, int iCell) { return -1; }
#endif
#if !SQLITE_OMIT_AUTOVACUUM
-/*
-** If the cell pCell, part of page pPage contains a pointer
-** to an overflow page, insert an entry into the pointer-map
-** for the overflow page.
-*/
-static void ptrmapPutOvflPtr( MemPage pPage, int pCell, ref int pRC )
-{
- if ( pRC != 0 )
- return;
- CellInfo info = new CellInfo();
- Debug.Assert( pCell != 0 );
- btreeParseCellPtr( pPage, pCell, ref info );
- Debug.Assert( ( info.nData + ( pPage.intKey != 0 ? 0 : info.nKey ) ) == info.nPayload );
- if ( info.iOverflow != 0 )
- {
- Pgno ovfl = sqlite3Get4byte( pPage.aData, pCell, info.iOverflow );
- ptrmapPut( pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC );
- }
-}
+ /*
+ ** If the cell pCell, part of page pPage contains a pointer
+ ** to an overflow page, insert an entry into the pointer-map
+ ** for the overflow page.
+ */
+ static void ptrmapPutOvflPtr(MemPage pPage, int pCell, ref int pRC) {
+ if (pRC != 0)
+ return;
+ CellInfo info = new CellInfo();
+ Debug.Assert(pCell != 0);
+ btreeParseCellPtr(pPage, pCell, ref info);
+ Debug.Assert((info.nData + (pPage.intKey != 0 ? 0 : info.nKey)) == info.nPayload);
+ if (info.iOverflow != 0) {
+ Pgno ovfl = sqlite3Get4byte(pPage.aData, pCell, info.iOverflow);
+ ptrmapPut(pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC);
+ }
+ }
-static void ptrmapPutOvflPtr( MemPage pPage, u8[] pCell, ref int pRC )
-{
- if ( pRC != 0 )
- return;
- CellInfo info = new CellInfo();
- Debug.Assert( pCell != null );
- btreeParseCellPtr( pPage, pCell, ref info );
- Debug.Assert( ( info.nData + ( pPage.intKey != 0 ? 0 : info.nKey ) ) == info.nPayload );
- if ( info.iOverflow != 0 )
- {
- Pgno ovfl = sqlite3Get4byte( pCell, info.iOverflow );
- ptrmapPut( pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC );
- }
-}
+ static void ptrmapPutOvflPtr(MemPage pPage, u8[] pCell, ref int pRC) {
+ if (pRC != 0)
+ return;
+ CellInfo info = new CellInfo();
+ Debug.Assert(pCell != null);
+ btreeParseCellPtr(pPage, pCell, ref info);
+ Debug.Assert((info.nData + (pPage.intKey != 0 ? 0 : info.nKey)) == info.nPayload);
+ if (info.iOverflow != 0) {
+ Pgno ovfl = sqlite3Get4byte(pCell, info.iOverflow);
+ ptrmapPut(pPage.pBt, ovfl, PTRMAP_OVERFLOW1, pPage.pgno, ref pRC);
+ }
+ }
#endif
-/*
-** Defragment the page given. All Cells are moved to the
-** end of the page and all free space is collected into one
-** big FreeBlk that occurs in between the header and cell
-** pointer array and the cell content area.
-*/
-static int defragmentPage( MemPage pPage )
-{
- int i; /* Loop counter */
- int pc; /* Address of a i-th cell */
- int addr; /* Offset of first byte after cell pointer array */
- int hdr; /* Offset to the page header */
- int size; /* Size of a cell */
- int usableSize; /* Number of usable bytes on a page */
- int cellOffset; /* Offset to the cell pointer array */
- int cbrk; /* Offset to the cell content area */
- int nCell; /* Number of cells on the page */
- byte[] data; /* The page data */
- byte[] temp; /* Temp area for cell content */
- int iCellFirst; /* First allowable cell index */
- int iCellLast; /* Last possible cell index */
-
-
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- Debug.Assert( pPage.pBt != null );
- Debug.Assert( pPage.pBt.usableSize <= SQLITE_MAX_PAGE_SIZE );
- Debug.Assert( pPage.nOverflow == 0 );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- temp = sqlite3PagerTempSpace( pPage.pBt.pPager );
- data = pPage.aData;
- hdr = pPage.hdrOffset;
- cellOffset = pPage.cellOffset;
- nCell = pPage.nCell;
- Debug.Assert( nCell == get2byte( data, hdr + 3 ) );
- usableSize = (int)pPage.pBt.usableSize;
- cbrk = get2byte( data, hdr + 5 );
- Buffer.BlockCopy( data, cbrk, temp, cbrk, usableSize - cbrk );//memcpy( temp[cbrk], ref data[cbrk], usableSize - cbrk );
- cbrk = usableSize;
- iCellFirst = cellOffset + 2 * nCell;
- iCellLast = usableSize - 4;
- for ( i = 0; i < nCell; i++ )
- {
- int pAddr; /* The i-th cell pointer */
- pAddr = cellOffset + i * 2; // &data[cellOffset + i * 2];
- pc = get2byte( data, pAddr );
- testcase( pc == iCellFirst );
- testcase( pc == iCellLast );
+ /*
+ ** Defragment the page given. All Cells are moved to the
+ ** end of the page and all free space is collected into one
+ ** big FreeBlk that occurs in between the header and cell
+ ** pointer array and the cell content area.
+ */
+ static int defragmentPage(MemPage pPage) {
+ int i; /* Loop counter */
+ int pc; /* Address of a i-th cell */
+ int addr; /* Offset of first byte after cell pointer array */
+ int hdr; /* Offset to the page header */
+ int size; /* Size of a cell */
+ int usableSize; /* Number of usable bytes on a page */
+ int cellOffset; /* Offset to the cell pointer array */
+ int cbrk; /* Offset to the cell content area */
+ int nCell; /* Number of cells on the page */
+ byte[] data; /* The page data */
+ byte[] temp; /* Temp area for cell content */
+ int iCellFirst; /* First allowable cell index */
+ int iCellLast; /* Last possible cell index */
+
+
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ Debug.Assert(pPage.pBt != null);
+ Debug.Assert(pPage.pBt.usableSize <= SQLITE_MAX_PAGE_SIZE);
+ Debug.Assert(pPage.nOverflow == 0);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ temp = sqlite3PagerTempSpace(pPage.pBt.pPager);
+ data = pPage.aData;
+ hdr = pPage.hdrOffset;
+ cellOffset = pPage.cellOffset;
+ nCell = pPage.nCell;
+ Debug.Assert(nCell == get2byte(data, hdr + 3));
+ usableSize = (int)pPage.pBt.usableSize;
+ cbrk = get2byte(data, hdr + 5);
+ Buffer.BlockCopy(data, cbrk, temp, cbrk, usableSize - cbrk);//memcpy( temp[cbrk], ref data[cbrk], usableSize - cbrk );
+ cbrk = usableSize;
+ iCellFirst = cellOffset + 2 * nCell;
+ iCellLast = usableSize - 4;
+ for (i = 0; i < nCell; i++) {
+ int pAddr; /* The i-th cell pointer */
+ pAddr = cellOffset + i * 2; // &data[cellOffset + i * 2];
+ pc = get2byte(data, pAddr);
+ testcase(pc == iCellFirst);
+ testcase(pc == iCellLast);
#if !(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
/* These conditions have already been verified in btreeInitPage()
** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
@@ -1346,737 +1252,670 @@ static int defragmentPage( MemPage pPage )
return SQLITE_CORRUPT_BKPT();
}
#endif
- Debug.Assert( pc >= iCellFirst && pc <= iCellLast );
- size = cellSizePtr( pPage, temp, pc );
- cbrk -= size;
+ Debug.Assert(pc >= iCellFirst && pc <= iCellLast);
+ size = cellSizePtr(pPage, temp, pc);
+ cbrk -= size;
#if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
- if ( cbrk < iCellFirst || pc + size > usableSize )
- {
- return SQLITE_CORRUPT_BKPT();
- }
+ if (cbrk < iCellFirst || pc + size > usableSize) {
+ return SQLITE_CORRUPT_BKPT();
+ }
#else
if ( cbrk < iCellFirst || pc + size > usableSize )
{
return SQLITE_CORRUPT_BKPT();
}
#endif
- Debug.Assert( cbrk + size <= usableSize && cbrk >= iCellFirst );
- testcase( cbrk + size == usableSize );
- testcase( pc + size == usableSize );
- Buffer.BlockCopy( temp, pc, data, cbrk, size );//memcpy(data[cbrk], ref temp[pc], size);
- put2byte( data, pAddr, cbrk );
- }
- Debug.Assert( cbrk >= iCellFirst );
- put2byte( data, hdr + 5, cbrk );
- data[hdr + 1] = 0;
- data[hdr + 2] = 0;
- data[hdr + 7] = 0;
- addr = cellOffset + 2 * nCell;
- Array.Clear( data, addr, cbrk - addr ); //memset(data[iCellFirst], 0, cbrk-iCellFirst);
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- if ( cbrk - iCellFirst != pPage.nFree )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- return SQLITE_OK;
-}
+ Debug.Assert(cbrk + size <= usableSize && cbrk >= iCellFirst);
+ testcase(cbrk + size == usableSize);
+ testcase(pc + size == usableSize);
+ Buffer.BlockCopy(temp, pc, data, cbrk, size);//memcpy(data[cbrk], ref temp[pc], size);
+ put2byte(data, pAddr, cbrk);
+ }
+ Debug.Assert(cbrk >= iCellFirst);
+ put2byte(data, hdr + 5, cbrk);
+ data[hdr + 1] = 0;
+ data[hdr + 2] = 0;
+ data[hdr + 7] = 0;
+ addr = cellOffset + 2 * nCell;
+ Array.Clear(data, addr, cbrk - addr); //memset(data[iCellFirst], 0, cbrk-iCellFirst);
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ if (cbrk - iCellFirst != pPage.nFree) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ return SQLITE_OK;
+ }
-/*
-** Allocate nByte bytes of space from within the B-Tree page passed
-** as the first argument. Write into pIdx the index into pPage.aData[]
-** of the first byte of allocated space. Return either SQLITE_OK or
-** an error code (usually SQLITE_CORRUPT).
-**
-** The caller guarantees that there is sufficient space to make the
-** allocation. This routine might need to defragment in order to bring
-** all the space together, however. This routine will avoid using
-** the first two bytes past the cell pointer area since presumably this
-** allocation is being made in order to insert a new cell, so we will
-** also end up needing a new cell pointer.
-*/
-static int allocateSpace( MemPage pPage, int nByte, ref int pIdx )
-{
- int hdr = pPage.hdrOffset; /* Local cache of pPage.hdrOffset */
- u8[] data = pPage.aData; /* Local cache of pPage.aData */
- int nFrag; /* Number of fragmented bytes on pPage */
- int top; /* First byte of cell content area */
- int gap; /* First byte of gap between cell pointers and cell content */
- int rc; /* Integer return code */
- u32 usableSize; /* Usable size of the page */
-
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- Debug.Assert( pPage.pBt != null );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( nByte >= 0 ); /* Minimum cell size is 4 */
- Debug.Assert( pPage.nFree >= nByte );
- Debug.Assert( pPage.nOverflow == 0 );
- usableSize = pPage.pBt.usableSize;
- Debug.Assert( nByte < usableSize - 8 );
-
- nFrag = data[hdr + 7];
- Debug.Assert( pPage.cellOffset == hdr + 12 - 4 * pPage.leaf );
- gap = pPage.cellOffset + 2 * pPage.nCell;
- top = get2byteNotZero( data, hdr + 5 );
- if ( gap > top )
- return SQLITE_CORRUPT_BKPT();
- testcase( gap + 2 == top );
- testcase( gap + 1 == top );
- testcase( gap == top );
-
- if ( nFrag >= 60 )
- {
- /* Always defragment highly fragmented pages */
- rc = defragmentPage( pPage );
- if ( rc != 0 )
- return rc;
- top = get2byteNotZero( data, hdr + 5 );
- }
- else if ( gap + 2 <= top )
- {
- /* Search the freelist looking for a free slot big enough to satisfy
- ** the request. The allocation is made from the first free slot in
- ** the list that is large enough to accomadate it.
- */
- int pc, addr;
- for ( addr = hdr + 1; ( pc = get2byte( data, addr ) ) > 0; addr = pc )
- {
- int size; /* Size of free slot */
- if ( pc > usableSize - 4 || pc < addr + 4 )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- size = get2byte( data, pc + 2 );
- if ( size >= nByte )
- {
- int x = size - nByte;
- testcase( x == 4 );
- testcase( x == 3 );
- if ( x < 4 )
- {
- /* Remove the slot from the free-list. Update the number of
- ** fragmented bytes within the page. */
- data[addr + 0] = data[pc + 0];
- data[addr + 1] = data[pc + 1]; //memcpy( data[addr], ref data[pc], 2 );
- data[hdr + 7] = (u8)( nFrag + x );
- }
- else if ( size + pc > usableSize )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- else
- {
- /* The slot remains on the free-list. Reduce its size to account
- ** for the portion used by the new allocation. */
- put2byte( data, pc + 2, x );
- }
- pIdx = pc + x;
- return SQLITE_OK;
- }
- }
- }
-
- /* Check to make sure there is enough space in the gap to satisfy
- ** the allocation. If not, defragment.
- */
- testcase( gap + 2 + nByte == top );
- if ( gap + 2 + nByte > top )
- {
- rc = defragmentPage( pPage );
- if ( rc != 0 )
- return rc;
- top = get2byteNotZero( data, hdr + 5 );
- Debug.Assert( gap + nByte <= top );
- }
-
-
- /* Allocate memory from the gap in between the cell pointer array
- ** and the cell content area. The btreeInitPage() call has already
- ** validated the freelist. Given that the freelist is valid, there
- ** is no way that the allocation can extend off the end of the page.
- ** The Debug.Assert() below verifies the previous sentence.
- */
- top -= nByte;
- put2byte( data, hdr + 5, top );
- Debug.Assert( top + nByte <= (int)pPage.pBt.usableSize );
- pIdx = top;
- return SQLITE_OK;
-}
+ /*
+ ** Allocate nByte bytes of space from within the B-Tree page passed
+ ** as the first argument. Write into pIdx the index into pPage.aData[]
+ ** of the first byte of allocated space. Return either SQLITE_OK or
+ ** an error code (usually SQLITE_CORRUPT).
+ **
+ ** The caller guarantees that there is sufficient space to make the
+ ** allocation. This routine might need to defragment in order to bring
+ ** all the space together, however. This routine will avoid using
+ ** the first two bytes past the cell pointer area since presumably this
+ ** allocation is being made in order to insert a new cell, so we will
+ ** also end up needing a new cell pointer.
+ */
+ static int allocateSpace(MemPage pPage, int nByte, ref int pIdx) {
+ int hdr = pPage.hdrOffset; /* Local cache of pPage.hdrOffset */
+ u8[] data = pPage.aData; /* Local cache of pPage.aData */
+ int nFrag; /* Number of fragmented bytes on pPage */
+ int top; /* First byte of cell content area */
+ int gap; /* First byte of gap between cell pointers and cell content */
+ int rc; /* Integer return code */
+ u32 usableSize; /* Usable size of the page */
+
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ Debug.Assert(pPage.pBt != null);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(nByte >= 0); /* Minimum cell size is 4 */
+ Debug.Assert(pPage.nFree >= nByte);
+ Debug.Assert(pPage.nOverflow == 0);
+ usableSize = pPage.pBt.usableSize;
+ Debug.Assert(nByte < usableSize - 8);
+
+ nFrag = data[hdr + 7];
+ Debug.Assert(pPage.cellOffset == hdr + 12 - 4 * pPage.leaf);
+ gap = pPage.cellOffset + 2 * pPage.nCell;
+ top = get2byteNotZero(data, hdr + 5);
+ if (gap > top)
+ return SQLITE_CORRUPT_BKPT();
+ testcase(gap + 2 == top);
+ testcase(gap + 1 == top);
+ testcase(gap == top);
+
+ if (nFrag >= 60) {
+ /* Always defragment highly fragmented pages */
+ rc = defragmentPage(pPage);
+ if (rc != 0)
+ return rc;
+ top = get2byteNotZero(data, hdr + 5);
+ } else if (gap + 2 <= top) {
+ /* Search the freelist looking for a free slot big enough to satisfy
+ ** the request. The allocation is made from the first free slot in
+ ** the list that is large enough to accomadate it.
+ */
+ int pc, addr;
+ for (addr = hdr + 1; (pc = get2byte(data, addr)) > 0; addr = pc) {
+ int size; /* Size of free slot */
+ if (pc > usableSize - 4 || pc < addr + 4) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ size = get2byte(data, pc + 2);
+ if (size >= nByte) {
+ int x = size - nByte;
+ testcase(x == 4);
+ testcase(x == 3);
+ if (x < 4) {
+ /* Remove the slot from the free-list. Update the number of
+ ** fragmented bytes within the page. */
+ data[addr + 0] = data[pc + 0];
+ data[addr + 1] = data[pc + 1]; //memcpy( data[addr], ref data[pc], 2 );
+ data[hdr + 7] = (u8)(nFrag + x);
+ } else if (size + pc > usableSize) {
+ return SQLITE_CORRUPT_BKPT();
+ } else {
+ /* The slot remains on the free-list. Reduce its size to account
+ ** for the portion used by the new allocation. */
+ put2byte(data, pc + 2, x);
+ }
+ pIdx = pc + x;
+ return SQLITE_OK;
+ }
+ }
+ }
-/*
-** Return a section of the pPage.aData to the freelist.
-** The first byte of the new free block is pPage.aDisk[start]
-** and the size of the block is "size" bytes.
-**
-** Most of the effort here is involved in coalesing adjacent
-** free blocks into a single big free block.
-*/
-static int freeSpace( MemPage pPage, u32 start, int size )
-{
- return freeSpace( pPage, (int)start, size );
-}
-static int freeSpace( MemPage pPage, int start, int size )
-{
- int addr, pbegin, hdr;
- int iLast; /* Largest possible freeblock offset */
- byte[] data = pPage.aData;
-
- Debug.Assert( pPage.pBt != null );
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- Debug.Assert( start >= pPage.hdrOffset + 6 + pPage.childPtrSize );
- Debug.Assert( ( start + size ) <= (int)pPage.pBt.usableSize );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( size >= 0 ); /* Minimum cell size is 4 */
-
- if ( pPage.pBt.secureDelete )
- {
- /* Overwrite deleted information with zeros when the secure_delete
- ** option is enabled */
- Array.Clear( data, start, size );// memset(&data[start], 0, size);
- }
-
- /* Add the space back into the linked list of freeblocks. Note that
- ** even though the freeblock list was checked by btreeInitPage(),
- ** btreeInitPage() did not detect overlapping cells or
- ** freeblocks that overlapped cells. Nor does it detect when the
- ** cell content area exceeds the value in the page header. If these
- ** situations arise, then subsequent insert operations might corrupt
- ** the freelist. So we do need to check for corruption while scanning
- ** the freelist.
- */
- hdr = pPage.hdrOffset;
- addr = hdr + 1;
- iLast = (int)pPage.pBt.usableSize - 4;
- Debug.Assert( start <= iLast );
- while ( ( pbegin = get2byte( data, addr ) ) < start && pbegin > 0 )
- {
- if ( pbegin < addr + 4 )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- addr = pbegin;
- }
- if ( pbegin > iLast )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- Debug.Assert( pbegin > addr || pbegin == 0 );
- put2byte( data, addr, start );
- put2byte( data, start, pbegin );
- put2byte( data, start + 2, size );
- pPage.nFree = (u16)( pPage.nFree + size );
-
- /* Coalesce adjacent free blocks */
- addr = hdr + 1;
- while ( ( pbegin = get2byte( data, addr ) ) > 0 )
- {
- int pnext, psize, x;
- Debug.Assert( pbegin > addr );
- Debug.Assert( pbegin <= (int)pPage.pBt.usableSize - 4 );
- pnext = get2byte( data, pbegin );
- psize = get2byte( data, pbegin + 2 );
- if ( pbegin + psize + 3 >= pnext && pnext > 0 )
- {
- int frag = pnext - ( pbegin + psize );
- if ( ( frag < 0 ) || ( frag > (int)data[hdr + 7] ) )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- data[hdr + 7] -= (u8)frag;
- x = get2byte( data, pnext );
- put2byte( data, pbegin, x );
- x = pnext + get2byte( data, pnext + 2 ) - pbegin;
- put2byte( data, pbegin + 2, x );
- }
- else
- {
- addr = pbegin;
- }
- }
-
- /* If the cell content area begins with a freeblock, remove it. */
- if ( data[hdr + 1] == data[hdr + 5] && data[hdr + 2] == data[hdr + 6] )
- {
- int top;
- pbegin = get2byte( data, hdr + 1 );
- put2byte( data, hdr + 1, get2byte( data, pbegin ) ); //memcpy( data[hdr + 1], ref data[pbegin], 2 );
- top = get2byte( data, hdr + 5 ) + get2byte( data, pbegin + 2 );
- put2byte( data, hdr + 5, top );
- }
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- return SQLITE_OK;
-}
+ /* Check to make sure there is enough space in the gap to satisfy
+ ** the allocation. If not, defragment.
+ */
+ testcase(gap + 2 + nByte == top);
+ if (gap + 2 + nByte > top) {
+ rc = defragmentPage(pPage);
+ if (rc != 0)
+ return rc;
+ top = get2byteNotZero(data, hdr + 5);
+ Debug.Assert(gap + nByte <= top);
+ }
-/*
-** Decode the flags byte (the first byte of the header) for a page
-** and initialize fields of the MemPage structure accordingly.
-**
-** Only the following combinations are supported. Anything different
-** indicates a corrupt database files:
-**
-** PTF_ZERODATA
-** PTF_ZERODATA | PTF_LEAF
-** PTF_LEAFDATA | PTF_INTKEY
-** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
-*/
-static int decodeFlags( MemPage pPage, int flagByte )
-{
- BtShared pBt; /* A copy of pPage.pBt */
-
- Debug.Assert( pPage.hdrOffset == ( pPage.pgno == 1 ? 100 : 0 ) );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- pPage.leaf = (u8)( flagByte >> 3 );
- Debug.Assert( PTF_LEAF == 1 << 3 );
- flagByte &= ~PTF_LEAF;
- pPage.childPtrSize = (u8)( 4 - 4 * pPage.leaf );
- pBt = pPage.pBt;
- if ( flagByte == ( PTF_LEAFDATA | PTF_INTKEY ) )
- {
- pPage.intKey = 1;
- pPage.hasData = pPage.leaf;
- pPage.maxLocal = pBt.maxLeaf;
- pPage.minLocal = pBt.minLeaf;
- }
- else if ( flagByte == PTF_ZERODATA )
- {
- pPage.intKey = 0;
- pPage.hasData = 0;
- pPage.maxLocal = pBt.maxLocal;
- pPage.minLocal = pBt.minLocal;
- }
- else
- {
- return SQLITE_CORRUPT_BKPT();
- }
- return SQLITE_OK;
-}
-/*
-** Initialize the auxiliary information for a disk block.
-**
-** Return SQLITE_OK on success. If we see that the page does
-** not contain a well-formed database page, then return
-** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
-** guarantee that the page is well-formed. It only shows that
-** we failed to detect any corruption.
-*/
-static int btreeInitPage( MemPage pPage )
-{
+ /* Allocate memory from the gap in between the cell pointer array
+ ** and the cell content area. The btreeInitPage() call has already
+ ** validated the freelist. Given that the freelist is valid, there
+ ** is no way that the allocation can extend off the end of the page.
+ ** The Debug.Assert() below verifies the previous sentence.
+ */
+ top -= nByte;
+ put2byte(data, hdr + 5, top);
+ Debug.Assert(top + nByte <= (int)pPage.pBt.usableSize);
+ pIdx = top;
+ return SQLITE_OK;
+ }
- Debug.Assert( pPage.pBt != null );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( pPage.pgno == sqlite3PagerPagenumber( pPage.pDbPage ) );
- Debug.Assert( pPage == sqlite3PagerGetExtra( pPage.pDbPage ) );
- Debug.Assert( pPage.aData == sqlite3PagerGetData( pPage.pDbPage ) );
-
- if ( 0 == pPage.isInit )
- {
- u16 pc; /* Address of a freeblock within pPage.aData[] */
- u8 hdr; /* Offset to beginning of page header */
- u8[] data; /* Equal to pPage.aData */
- BtShared pBt; /* The main btree structure */
- int usableSize; /* Amount of usable space on each page */
- u16 cellOffset; /* Offset from start of page to first cell pointer */
- int nFree; /* Number of unused bytes on the page */
- int top; /* First byte of the cell content area */
- int iCellFirst; /* First allowable cell or freeblock offset */
- int iCellLast; /* Last possible cell or freeblock offset */
-
- pBt = pPage.pBt;
-
- hdr = pPage.hdrOffset;
- data = pPage.aData;
- if ( decodeFlags( pPage, data[hdr] ) != 0 )
- return SQLITE_CORRUPT_BKPT();
- Debug.Assert( pBt.pageSize >= 512 && pBt.pageSize <= 65536 );
- pPage.maskPage = (u16)( pBt.pageSize - 1 );
- pPage.nOverflow = 0;
- usableSize = (int)pBt.usableSize;
- pPage.cellOffset = ( cellOffset = (u16)( hdr + 12 - 4 * pPage.leaf ) );
- top = get2byteNotZero( data, hdr + 5 );
- pPage.nCell = (u16)( get2byte( data, hdr + 3 ) );
- if ( pPage.nCell > MX_CELL( pBt ) )
- {
- /* To many cells for a single page. The page must be corrupt */
- return SQLITE_CORRUPT_BKPT();
- }
- testcase( pPage.nCell == MX_CELL( pBt ) );
-
- /* A malformed database page might cause us to read past the end
- ** of page when parsing a cell.
- **
- ** The following block of code checks early to see if a cell extends
- ** past the end of a page boundary and causes SQLITE_CORRUPT to be
- ** returned if it does.
- */
- iCellFirst = cellOffset + 2 * pPage.nCell;
- iCellLast = usableSize - 4;
+ /*
+ ** Return a section of the pPage.aData to the freelist.
+ ** The first byte of the new free block is pPage.aDisk[start]
+ ** and the size of the block is "size" bytes.
+ **
+ ** Most of the effort here is involved in coalesing adjacent
+ ** free blocks into a single big free block.
+ */
+ static int freeSpace(MemPage pPage, u32 start, int size) {
+ return freeSpace(pPage, (int)start, size);
+ }
+ static int freeSpace(MemPage pPage, int start, int size) {
+ int addr, pbegin, hdr;
+ int iLast; /* Largest possible freeblock offset */
+ byte[] data = pPage.aData;
+
+ Debug.Assert(pPage.pBt != null);
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ Debug.Assert(start >= pPage.hdrOffset + 6 + pPage.childPtrSize);
+ Debug.Assert((start + size) <= (int)pPage.pBt.usableSize);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(size >= 0); /* Minimum cell size is 4 */
+
+ if (pPage.pBt.secureDelete) {
+ /* Overwrite deleted information with zeros when the secure_delete
+ ** option is enabled */
+ Array.Clear(data, start, size);// memset(&data[start], 0, size);
+ }
+
+ /* Add the space back into the linked list of freeblocks. Note that
+ ** even though the freeblock list was checked by btreeInitPage(),
+ ** btreeInitPage() did not detect overlapping cells or
+ ** freeblocks that overlapped cells. Nor does it detect when the
+ ** cell content area exceeds the value in the page header. If these
+ ** situations arise, then subsequent insert operations might corrupt
+ ** the freelist. So we do need to check for corruption while scanning
+ ** the freelist.
+ */
+ hdr = pPage.hdrOffset;
+ addr = hdr + 1;
+ iLast = (int)pPage.pBt.usableSize - 4;
+ Debug.Assert(start <= iLast);
+ while ((pbegin = get2byte(data, addr)) < start && pbegin > 0) {
+ if (pbegin < addr + 4) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ addr = pbegin;
+ }
+ if (pbegin > iLast) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ Debug.Assert(pbegin > addr || pbegin == 0);
+ put2byte(data, addr, start);
+ put2byte(data, start, pbegin);
+ put2byte(data, start + 2, size);
+ pPage.nFree = (u16)(pPage.nFree + size);
+
+ /* Coalesce adjacent free blocks */
+ addr = hdr + 1;
+ while ((pbegin = get2byte(data, addr)) > 0) {
+ int pnext, psize, x;
+ Debug.Assert(pbegin > addr);
+ Debug.Assert(pbegin <= (int)pPage.pBt.usableSize - 4);
+ pnext = get2byte(data, pbegin);
+ psize = get2byte(data, pbegin + 2);
+ if (pbegin + psize + 3 >= pnext && pnext > 0) {
+ int frag = pnext - (pbegin + psize);
+ if ((frag < 0) || (frag > (int)data[hdr + 7])) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ data[hdr + 7] -= (u8)frag;
+ x = get2byte(data, pnext);
+ put2byte(data, pbegin, x);
+ x = pnext + get2byte(data, pnext + 2) - pbegin;
+ put2byte(data, pbegin + 2, x);
+ } else {
+ addr = pbegin;
+ }
+ }
+
+ /* If the cell content area begins with a freeblock, remove it. */
+ if (data[hdr + 1] == data[hdr + 5] && data[hdr + 2] == data[hdr + 6]) {
+ int top;
+ pbegin = get2byte(data, hdr + 1);
+ put2byte(data, hdr + 1, get2byte(data, pbegin)); //memcpy( data[hdr + 1], ref data[pbegin], 2 );
+ top = get2byte(data, hdr + 5) + get2byte(data, pbegin + 2);
+ put2byte(data, hdr + 5, top);
+ }
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ return SQLITE_OK;
+ }
+
+ /*
+ ** Decode the flags byte (the first byte of the header) for a page
+ ** and initialize fields of the MemPage structure accordingly.
+ **
+ ** Only the following combinations are supported. Anything different
+ ** indicates a corrupt database files:
+ **
+ ** PTF_ZERODATA
+ ** PTF_ZERODATA | PTF_LEAF
+ ** PTF_LEAFDATA | PTF_INTKEY
+ ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
+ */
+ static int decodeFlags(MemPage pPage, int flagByte) {
+ BtShared pBt; /* A copy of pPage.pBt */
+
+ Debug.Assert(pPage.hdrOffset == (pPage.pgno == 1 ? 100 : 0));
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ pPage.leaf = (u8)(flagByte >> 3);
+ Debug.Assert(PTF_LEAF == 1 << 3);
+ flagByte &= ~PTF_LEAF;
+ pPage.childPtrSize = (u8)(4 - 4 * pPage.leaf);
+ pBt = pPage.pBt;
+ if (flagByte == (PTF_LEAFDATA | PTF_INTKEY)) {
+ pPage.intKey = 1;
+ pPage.hasData = pPage.leaf;
+ pPage.maxLocal = pBt.maxLeaf;
+ pPage.minLocal = pBt.minLeaf;
+ } else if (flagByte == PTF_ZERODATA) {
+ pPage.intKey = 0;
+ pPage.hasData = 0;
+ pPage.maxLocal = pBt.maxLocal;
+ pPage.minLocal = pBt.minLocal;
+ } else {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ return SQLITE_OK;
+ }
+
+ /*
+ ** Initialize the auxiliary information for a disk block.
+ **
+ ** Return SQLITE_OK on success. If we see that the page does
+ ** not contain a well-formed database page, then return
+ ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
+ ** guarantee that the page is well-formed. It only shows that
+ ** we failed to detect any corruption.
+ */
+ static int btreeInitPage(MemPage pPage) {
+
+ Debug.Assert(pPage.pBt != null);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(pPage.pgno == sqlite3PagerPagenumber(pPage.pDbPage));
+ Debug.Assert(pPage == sqlite3PagerGetExtra(pPage.pDbPage));
+ Debug.Assert(pPage.aData == sqlite3PagerGetData(pPage.pDbPage));
+
+ if (0 == pPage.isInit) {
+ u16 pc; /* Address of a freeblock within pPage.aData[] */
+ u8 hdr; /* Offset to beginning of page header */
+ u8[] data; /* Equal to pPage.aData */
+ BtShared pBt; /* The main btree structure */
+ int usableSize; /* Amount of usable space on each page */
+ u16 cellOffset; /* Offset from start of page to first cell pointer */
+ int nFree; /* Number of unused bytes on the page */
+ int top; /* First byte of the cell content area */
+ int iCellFirst; /* First allowable cell or freeblock offset */
+ int iCellLast; /* Last possible cell or freeblock offset */
+
+ pBt = pPage.pBt;
+
+ hdr = pPage.hdrOffset;
+ data = pPage.aData;
+ if (decodeFlags(pPage, data[hdr]) != 0)
+ return SQLITE_CORRUPT_BKPT();
+ Debug.Assert(pBt.pageSize >= 512 && pBt.pageSize <= 65536);
+ pPage.maskPage = (u16)(pBt.pageSize - 1);
+ pPage.nOverflow = 0;
+ usableSize = (int)pBt.usableSize;
+ pPage.cellOffset = (cellOffset = (u16)(hdr + 12 - 4 * pPage.leaf));
+ top = get2byteNotZero(data, hdr + 5);
+ pPage.nCell = (u16)(get2byte(data, hdr + 3));
+ if (pPage.nCell > MX_CELL(pBt)) {
+ /* To many cells for a single page. The page must be corrupt */
+ return SQLITE_CORRUPT_BKPT();
+ }
+ testcase(pPage.nCell == MX_CELL(pBt));
+
+ /* A malformed database page might cause us to read past the end
+ ** of page when parsing a cell.
+ **
+ ** The following block of code checks early to see if a cell extends
+ ** past the end of a page boundary and causes SQLITE_CORRUPT to be
+ ** returned if it does.
+ */
+ iCellFirst = cellOffset + 2 * pPage.nCell;
+ iCellLast = usableSize - 4;
#if (SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
- {
- int i; /* Index into the cell pointer array */
- int sz; /* Size of a cell */
-
- if ( 0 == pPage.leaf )
- iCellLast--;
- for ( i = 0; i < pPage.nCell; i++ )
- {
- pc = (u16)get2byte( data, cellOffset + i * 2 );
- testcase( pc == iCellFirst );
- testcase( pc == iCellLast );
- if ( pc < iCellFirst || pc > iCellLast )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- sz = cellSizePtr( pPage, data, pc );
- testcase( pc + sz == usableSize );
- if ( pc + sz > usableSize )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- }
- if ( 0 == pPage.leaf )
- iCellLast++;
- }
+ {
+ int i; /* Index into the cell pointer array */
+ int sz; /* Size of a cell */
+
+ if (0 == pPage.leaf)
+ iCellLast--;
+ for (i = 0; i < pPage.nCell; i++) {
+ pc = (u16)get2byte(data, cellOffset + i * 2);
+ testcase(pc == iCellFirst);
+ testcase(pc == iCellLast);
+ if (pc < iCellFirst || pc > iCellLast) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ sz = cellSizePtr(pPage, data, pc);
+ testcase(pc + sz == usableSize);
+ if (pc + sz > usableSize) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ }
+ if (0 == pPage.leaf)
+ iCellLast++;
+ }
#endif
- /* Compute the total free space on the page */
- pc = (u16)get2byte( data, hdr + 1 );
- nFree = (u16)( data[hdr + 7] + top );
- while ( pc > 0 )
- {
- u16 next, size;
- if ( pc < iCellFirst || pc > iCellLast )
- {
- /* Start of free block is off the page */
- return SQLITE_CORRUPT_BKPT();
- }
- next = (u16)get2byte( data, pc );
- size = (u16)get2byte( data, pc + 2 );
- if ( ( next > 0 && next <= pc + size + 3 ) || pc + size > usableSize )
- {
- /* Free blocks must be in ascending order. And the last byte of
- ** the free-block must lie on the database page. */
- return SQLITE_CORRUPT_BKPT();
- }
- nFree = (u16)( nFree + size );
- pc = next;
- }
+ /* Compute the total free space on the page */
+ pc = (u16)get2byte(data, hdr + 1);
+ nFree = (u16)(data[hdr + 7] + top);
+ while (pc > 0) {
+ u16 next, size;
+ if (pc < iCellFirst || pc > iCellLast) {
+ /* Start of free block is off the page */
+ return SQLITE_CORRUPT_BKPT();
+ }
+ next = (u16)get2byte(data, pc);
+ size = (u16)get2byte(data, pc + 2);
+ if ((next > 0 && next <= pc + size + 3) || pc + size > usableSize) {
+ /* Free blocks must be in ascending order. And the last byte of
+ ** the free-block must lie on the database page. */
+ return SQLITE_CORRUPT_BKPT();
+ }
+ nFree = (u16)(nFree + size);
+ pc = next;
+ }
+
+ /* At this point, nFree contains the sum of the offset to the start
+ ** of the cell-content area plus the number of free bytes within
+ ** the cell-content area. If this is greater than the usable-size
+ ** of the page, then the page must be corrupted. This check also
+ ** serves to verify that the offset to the start of the cell-content
+ ** area, according to the page header, lies within the page.
+ */
+ if (nFree > usableSize) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ pPage.nFree = (u16)(nFree - iCellFirst);
+ pPage.isInit = 1;
+ }
+ return SQLITE_OK;
+ }
- /* At this point, nFree contains the sum of the offset to the start
- ** of the cell-content area plus the number of free bytes within
- ** the cell-content area. If this is greater than the usable-size
- ** of the page, then the page must be corrupted. This check also
- ** serves to verify that the offset to the start of the cell-content
- ** area, according to the page header, lies within the page.
- */
- if ( nFree > usableSize )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- pPage.nFree = (u16)( nFree - iCellFirst );
- pPage.isInit = 1;
- }
- return SQLITE_OK;
-}
+ /*
+ ** Set up a raw page so that it looks like a database page holding
+ ** no entries.
+ */
+ static void zeroPage(MemPage pPage, int flags) {
+ byte[] data = pPage.aData;
+ BtShared pBt = pPage.pBt;
+ u8 hdr = pPage.hdrOffset;
+ u16 first;
+
+ Debug.Assert(sqlite3PagerPagenumber(pPage.pDbPage) == pPage.pgno);
+ Debug.Assert(sqlite3PagerGetExtra(pPage.pDbPage) == pPage);
+ Debug.Assert(sqlite3PagerGetData(pPage.pDbPage) == data);
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ if (pBt.secureDelete) {
+ Array.Clear(data, hdr, (int)(pBt.usableSize - hdr));//memset(&data[hdr], 0, pBt->usableSize - hdr);
+ }
-/*
-** Set up a raw page so that it looks like a database page holding
-** no entries.
-*/
-static void zeroPage( MemPage pPage, int flags )
-{
- byte[] data = pPage.aData;
- BtShared pBt = pPage.pBt;
- u8 hdr = pPage.hdrOffset;
- u16 first;
-
- Debug.Assert( sqlite3PagerPagenumber( pPage.pDbPage ) == pPage.pgno );
- Debug.Assert( sqlite3PagerGetExtra( pPage.pDbPage ) == pPage );
- Debug.Assert( sqlite3PagerGetData( pPage.pDbPage ) == data );
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- if ( pBt.secureDelete )
- {
- Array.Clear( data, hdr, (int)( pBt.usableSize - hdr ) );//memset(&data[hdr], 0, pBt->usableSize - hdr);
- }
-
- data[hdr] = (u8)flags;
- first = (u16)( hdr + 8 + 4 * ( ( flags & PTF_LEAF ) == 0 ? 1 : 0 ) );
- Array.Clear( data, hdr + 1, 4 );//memset(data[hdr+1], 0, 4);
- data[hdr + 7] = 0;
- put2byte( data, hdr + 5, pBt.usableSize );
- pPage.nFree = (u16)( pBt.usableSize - first );
- decodeFlags( pPage, flags );
- pPage.hdrOffset = hdr;
- pPage.cellOffset = first;
- pPage.nOverflow = 0;
- Debug.Assert( pBt.pageSize >= 512 && pBt.pageSize <= 65536 );
- pPage.maskPage = (u16)( pBt.pageSize - 1 );
- pPage.nCell = 0;
- pPage.isInit = 1;
-}
+ data[hdr] = (u8)flags;
+ first = (u16)(hdr + 8 + 4 * ((flags & PTF_LEAF) == 0 ? 1 : 0));
+ Array.Clear(data, hdr + 1, 4);//memset(data[hdr+1], 0, 4);
+ data[hdr + 7] = 0;
+ put2byte(data, hdr + 5, pBt.usableSize);
+ pPage.nFree = (u16)(pBt.usableSize - first);
+ decodeFlags(pPage, flags);
+ pPage.hdrOffset = hdr;
+ pPage.cellOffset = first;
+ pPage.nOverflow = 0;
+ Debug.Assert(pBt.pageSize >= 512 && pBt.pageSize <= 65536);
+ pPage.maskPage = (u16)(pBt.pageSize - 1);
+ pPage.nCell = 0;
+ pPage.isInit = 1;
+ }
-/*
-** Convert a DbPage obtained from the pager into a MemPage used by
-** the btree layer.
-*/
-static MemPage btreePageFromDbPage( DbPage pDbPage, Pgno pgno, BtShared pBt )
-{
- MemPage pPage = (MemPage)sqlite3PagerGetExtra( pDbPage );
- pPage.aData = sqlite3PagerGetData( pDbPage );
- pPage.pDbPage = pDbPage;
- pPage.pBt = pBt;
- pPage.pgno = pgno;
- pPage.hdrOffset = (u8)( pPage.pgno == 1 ? 100 : 0 );
- return pPage;
-}
+ /*
+ ** Convert a DbPage obtained from the pager into a MemPage used by
+ ** the btree layer.
+ */
+ static MemPage btreePageFromDbPage(DbPage pDbPage, Pgno pgno, BtShared pBt) {
+ MemPage pPage = (MemPage)sqlite3PagerGetExtra(pDbPage);
+ pPage.aData = sqlite3PagerGetData(pDbPage);
+ pPage.pDbPage = pDbPage;
+ pPage.pBt = pBt;
+ pPage.pgno = pgno;
+ pPage.hdrOffset = (u8)(pPage.pgno == 1 ? 100 : 0);
+ return pPage;
+ }
-/*
-** Get a page from the pager. Initialize the MemPage.pBt and
-** MemPage.aData elements if needed.
-**
-** If the noContent flag is set, it means that we do not care about
-** the content of the page at this time. So do not go to the disk
-** to fetch the content. Just fill in the content with zeros for now.
-** If in the future we call sqlite3PagerWrite() on this page, that
-** means we have started to be concerned about content and the disk
-** read should occur at that point.
-*/
-static int btreeGetPage(
-BtShared pBt, /* The btree */
-Pgno pgno, /* Number of the page to fetch */
-ref MemPage ppPage, /* Return the page in this parameter */
-int noContent /* Do not load page content if true */
-)
-{
- int rc;
- DbPage pDbPage = null;
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- rc = sqlite3PagerAcquire( pBt.pPager, pgno, ref pDbPage, (u8)noContent );
- if ( rc != 0 )
- return rc;
- ppPage = btreePageFromDbPage( pDbPage, pgno, pBt );
- return SQLITE_OK;
-}
+ /*
+ ** Get a page from the pager. Initialize the MemPage.pBt and
+ ** MemPage.aData elements if needed.
+ **
+ ** If the noContent flag is set, it means that we do not care about
+ ** the content of the page at this time. So do not go to the disk
+ ** to fetch the content. Just fill in the content with zeros for now.
+ ** If in the future we call sqlite3PagerWrite() on this page, that
+ ** means we have started to be concerned about content and the disk
+ ** read should occur at that point.
+ */
+ static int btreeGetPage(
+ BtShared pBt, /* The btree */
+ Pgno pgno, /* Number of the page to fetch */
+ ref MemPage ppPage, /* Return the page in this parameter */
+ int noContent /* Do not load page content if true */
+ ) {
+ int rc;
+ DbPage pDbPage = null;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ rc = sqlite3PagerAcquire(pBt.pPager, pgno, ref pDbPage, (u8)noContent);
+ if (rc != 0)
+ return rc;
+ ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
+ return SQLITE_OK;
+ }
-/*
-** Retrieve a page from the pager cache. If the requested page is not
-** already in the pager cache return NULL. Initialize the MemPage.pBt and
-** MemPage.aData elements if needed.
-*/
-static MemPage btreePageLookup( BtShared pBt, Pgno pgno )
-{
- DbPage pDbPage;
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- pDbPage = sqlite3PagerLookup( pBt.pPager, pgno );
- if ( pDbPage )
- {
- return btreePageFromDbPage( pDbPage, pgno, pBt );
- }
- return null;
-}
+ /*
+ ** Retrieve a page from the pager cache. If the requested page is not
+ ** already in the pager cache return NULL. Initialize the MemPage.pBt and
+ ** MemPage.aData elements if needed.
+ */
+ static MemPage btreePageLookup(BtShared pBt, Pgno pgno) {
+ DbPage pDbPage;
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ pDbPage = sqlite3PagerLookup(pBt.pPager, pgno);
+ if (pDbPage) {
+ return btreePageFromDbPage(pDbPage, pgno, pBt);
+ }
+ return null;
+ }
-/*
-** Return the size of the database file in pages. If there is any kind of
-** error, return ((unsigned int)-1).
-*/
-static Pgno btreePagecount( BtShared pBt )
-{
- return pBt.nPage;
-}
-static Pgno sqlite3BtreeLastPage( Btree p )
-{
- Debug.Assert( sqlite3BtreeHoldsMutex( p ) );
- Debug.Assert( ( ( p.pBt.nPage ) & 0x8000000 ) == 0 );
- return (Pgno)btreePagecount( p.pBt );
-}
+ /*
+ ** Return the size of the database file in pages. If there is any kind of
+ ** error, return ((unsigned int)-1).
+ */
+ static Pgno btreePagecount(BtShared pBt) {
+ return pBt.nPage;
+ }
+ static Pgno sqlite3BtreeLastPage(Btree p) {
+ Debug.Assert(sqlite3BtreeHoldsMutex(p));
+ Debug.Assert(((p.pBt.nPage) & 0x8000000) == 0);
+ return (Pgno)btreePagecount(p.pBt);
+ }
-/*
-** Get a page from the pager and initialize it. This routine is just a
-** convenience wrapper around separate calls to btreeGetPage() and
-** btreeInitPage().
-**
-** If an error occurs, then the value ppPage is set to is undefined. It
-** may remain unchanged, or it may be set to an invalid value.
-*/
-static int getAndInitPage(
-BtShared pBt, /* The database file */
-Pgno pgno, /* Number of the page to get */
-ref MemPage ppPage /* Write the page pointer here */
-)
-{
- int rc;
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
-
- if ( pgno > btreePagecount( pBt ) )
- {
- rc = SQLITE_CORRUPT_BKPT();
- }
- else
- {
- rc = btreeGetPage( pBt, pgno, ref ppPage, 0 );
- if ( rc == SQLITE_OK )
- {
- rc = btreeInitPage( ppPage );
- if ( rc != SQLITE_OK )
- {
- releasePage( ppPage );
- }
- }
- }
+ /*
+ ** Get a page from the pager and initialize it. This routine is just a
+ ** convenience wrapper around separate calls to btreeGetPage() and
+ ** btreeInitPage().
+ **
+ ** If an error occurs, then the value ppPage is set to is undefined. It
+ ** may remain unchanged, or it may be set to an invalid value.
+ */
+ static int getAndInitPage(
+ BtShared pBt, /* The database file */
+ Pgno pgno, /* Number of the page to get */
+ ref MemPage ppPage /* Write the page pointer here */
+ ) {
+ int rc;
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+
+ if (pgno > btreePagecount(pBt)) {
+ rc = SQLITE_CORRUPT_BKPT();
+ } else {
+ rc = btreeGetPage(pBt, pgno, ref ppPage, 0);
+ if (rc == SQLITE_OK) {
+ rc = btreeInitPage(ppPage);
+ if (rc != SQLITE_OK) {
+ releasePage(ppPage);
+ }
+ }
+ }
- testcase( pgno == 0 );
- Debug.Assert( pgno != 0 || rc == SQLITE_CORRUPT );
+ testcase(pgno == 0);
+ Debug.Assert(pgno != 0 || rc == SQLITE_CORRUPT);
- return rc;
-}
+ return rc;
+ }
-/*
-** Release a MemPage. This should be called once for each prior
-** call to btreeGetPage.
-*/
-static void releasePage( MemPage pPage )
-{
- if ( pPage != null )
- {
- Debug.Assert( pPage.aData != null );
- Debug.Assert( pPage.pBt != null );
- //TODO -- find out why corrupt9 & diskfull fail on this tests
- //Debug.Assert( sqlite3PagerGetExtra( pPage.pDbPage ) == pPage );
- //Debug.Assert( sqlite3PagerGetData( pPage.pDbPage ) == pPage.aData );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- sqlite3PagerUnref( pPage.pDbPage );
- }
-}
+ /*
+ ** Release a MemPage. This should be called once for each prior
+ ** call to btreeGetPage.
+ */
+ static void releasePage(MemPage pPage) {
+ if (pPage != null) {
+ Debug.Assert(pPage.aData != null);
+ Debug.Assert(pPage.pBt != null);
+ //TODO -- find out why corrupt9 & diskfull fail on this tests
+ //Debug.Assert( sqlite3PagerGetExtra( pPage.pDbPage ) == pPage );
+ //Debug.Assert( sqlite3PagerGetData( pPage.pDbPage ) == pPage.aData );
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ sqlite3PagerUnref(pPage.pDbPage);
+ }
+ }
-/*
-** During a rollback, when the pager reloads information into the cache
-** so that the cache is restored to its original state at the start of
-** the transaction, for each page restored this routine is called.
-**
-** This routine needs to reset the extra data section at the end of the
-** page to agree with the restored data.
-*/
-static void pageReinit( DbPage pData )
-{
- MemPage pPage;
- pPage = sqlite3PagerGetExtra( pData );
- Debug.Assert( sqlite3PagerPageRefcount( pData ) > 0 );
- if ( pPage.isInit != 0 )
- {
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- pPage.isInit = 0;
- if ( sqlite3PagerPageRefcount( pData ) > 1 )
- {
- /* pPage might not be a btree page; it might be an overflow page
- ** or ptrmap page or a free page. In those cases, the following
- ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
- ** But no harm is done by this. And it is very important that
- ** btreeInitPage() be called on every btree page so we make
- ** the call for every page that comes in for re-initing. */
- btreeInitPage( pPage );
- }
- }
-}
+ /*
+ ** During a rollback, when the pager reloads information into the cache
+ ** so that the cache is restored to its original state at the start of
+ ** the transaction, for each page restored this routine is called.
+ **
+ ** This routine needs to reset the extra data section at the end of the
+ ** page to agree with the restored data.
+ */
+ static void pageReinit(DbPage pData) {
+ MemPage pPage;
+ pPage = sqlite3PagerGetExtra(pData);
+ Debug.Assert(sqlite3PagerPageRefcount(pData) > 0);
+ if (pPage.isInit != 0) {
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ pPage.isInit = 0;
+ if (sqlite3PagerPageRefcount(pData) > 1) {
+ /* pPage might not be a btree page; it might be an overflow page
+ ** or ptrmap page or a free page. In those cases, the following
+ ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
+ ** But no harm is done by this. And it is very important that
+ ** btreeInitPage() be called on every btree page so we make
+ ** the call for every page that comes in for re-initing. */
+ btreeInitPage(pPage);
+ }
+ }
+ }
-/*
-** Invoke the busy handler for a btree.
-*/
-static int btreeInvokeBusyHandler( object pArg )
-{
- BtShared pBt = (BtShared)pArg;
- Debug.Assert( pBt.db != null );
- Debug.Assert( sqlite3_mutex_held( pBt.db.mutex ) );
- return sqlite3InvokeBusyHandler( pBt.db.busyHandler );
-}
+ /*
+ ** Invoke the busy handler for a btree.
+ */
+ static int btreeInvokeBusyHandler(object pArg) {
+ BtShared pBt = (BtShared)pArg;
+ Debug.Assert(pBt.db != null);
+ Debug.Assert(sqlite3_mutex_held(pBt.db.mutex));
+ return sqlite3InvokeBusyHandler(pBt.db.busyHandler);
+ }
-/*
-** Open a database file.
-**
-** zFilename is the name of the database file. If zFilename is NULL
-** then an ephemeral database is created. The ephemeral database might
-** be exclusively in memory, or it might use a disk-based memory cache.
-** Either way, the ephemeral database will be automatically deleted
-** when sqlite3BtreeClose() is called.
-**
-** If zFilename is ":memory:" then an in-memory database is created
-** that is automatically destroyed when it is closed.
-**
-** The "flags" parameter is a bitmask that might contain bits
-** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
-** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
-** These flags are passed through into sqlite3PagerOpen() and must
-** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
-**
-** If the database is already opened in the same database connection
-** and we are in shared cache mode, then the open will fail with an
-** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
-** objects in the same database connection since doing so will lead
-** to problems with locking.
-*/
-static int sqlite3BtreeOpen(
-sqlite3_vfs pVfs, /* VFS to use for this b-tree */
-string zFilename, /* Name of the file containing the BTree database */
-sqlite3 db, /* Associated database handle */
-ref Btree ppBtree, /* Pointer to new Btree object written here */
-int flags, /* Options */
-int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
-)
-{
- BtShared pBt = null; /* Shared part of btree structure */
- Btree p; /* Handle to return */
- sqlite3_mutex mutexOpen = null; /* Prevents a race condition. Ticket #3537 */
- int rc = SQLITE_OK; /* Result code from this function */
- u8 nReserve; /* Byte of unused space on each page */
- byte[] zDbHeader = new byte[100]; /* Database header content */
-
- /* True if opening an ephemeral, temporary database */
- bool isTempDb = String.IsNullOrEmpty( zFilename );//zFilename==0 || zFilename[0]==0;
-
- /* Set the variable isMemdb to true for an in-memory database, or
- ** false for a file-based database.
- */
+ /*
+ ** Open a database file.
+ **
+ ** zFilename is the name of the database file. If zFilename is NULL
+ ** then an ephemeral database is created. The ephemeral database might
+ ** be exclusively in memory, or it might use a disk-based memory cache.
+ ** Either way, the ephemeral database will be automatically deleted
+ ** when sqlite3BtreeClose() is called.
+ **
+ ** If zFilename is ":memory:" then an in-memory database is created
+ ** that is automatically destroyed when it is closed.
+ **
+ ** The "flags" parameter is a bitmask that might contain bits
+ ** BTREE_OMIT_JOURNAL and/or BTREE_NO_READLOCK. The BTREE_NO_READLOCK
+ ** bit is also set if the SQLITE_NoReadlock flags is set in db->flags.
+ ** These flags are passed through into sqlite3PagerOpen() and must
+ ** be the same values as PAGER_OMIT_JOURNAL and PAGER_NO_READLOCK.
+ **
+ ** If the database is already opened in the same database connection
+ ** and we are in shared cache mode, then the open will fail with an
+ ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
+ ** objects in the same database connection since doing so will lead
+ ** to problems with locking.
+ */
+ static int sqlite3BtreeOpen(
+ sqlite3_vfs pVfs, /* VFS to use for this b-tree */
+ string zFilename, /* Name of the file containing the BTree database */
+ sqlite3 db, /* Associated database handle */
+ ref Btree ppBtree, /* Pointer to new Btree object written here */
+ int flags, /* Options */
+ int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
+ ) {
+ BtShared pBt = null; /* Shared part of btree structure */
+ Btree p; /* Handle to return */
+ sqlite3_mutex mutexOpen = null; /* Prevents a race condition. Ticket #3537 */
+ int rc = SQLITE_OK; /* Result code from this function */
+ u8 nReserve; /* Byte of unused space on each page */
+ byte[] zDbHeader = new byte[100]; /* Database header content */
+
+ /* True if opening an ephemeral, temporary database */
+ bool isTempDb = String.IsNullOrEmpty(zFilename);//zFilename==0 || zFilename[0]==0;
+
+ /* Set the variable isMemdb to true for an in-memory database, or
+ ** false for a file-based database.
+ */
#if SQLITE_OMIT_MEMORYDB
bool isMemdb = false;
#else
- bool isMemdb = ( zFilename == ":memory:" )
- || ( isTempDb && sqlite3TempInMemory( db ) );
+ bool isMemdb = (zFilename == ":memory:")
+ || (isTempDb && sqlite3TempInMemory(db));
#endif
- Debug.Assert( db != null );
- Debug.Assert( pVfs != null );
- Debug.Assert( sqlite3_mutex_held( db.mutex ) );
- Debug.Assert( ( flags & 0xff ) == flags ); /* flags fit in 8 bits */
-
- /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
- Debug.Assert( ( flags & BTREE_UNORDERED ) == 0 || ( flags & BTREE_SINGLE ) != 0 );
-
- /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
- Debug.Assert( ( flags & BTREE_SINGLE ) == 0 || isTempDb );
-
- if ( ( db.flags & SQLITE_NoReadlock ) != 0 )
- {
- flags |= BTREE_NO_READLOCK;
- }
- if ( isMemdb )
- {
- flags |= BTREE_MEMORY;
- }
- if ( ( vfsFlags & SQLITE_OPEN_MAIN_DB ) != 0 && ( isMemdb || isTempDb ) )
- {
- vfsFlags = ( vfsFlags & ~SQLITE_OPEN_MAIN_DB ) | SQLITE_OPEN_TEMP_DB;
- }
-
- p = new Btree();//sqlite3MallocZero(sizeof(Btree));
- //if( !p ){
- // return SQLITE_NOMEM;
- //}
- p.inTrans = TRANS_NONE;
- p.db = db;
+ Debug.Assert(db != null);
+ Debug.Assert(pVfs != null);
+ Debug.Assert(sqlite3_mutex_held(db.mutex));
+ Debug.Assert((flags & 0xff) == flags); /* flags fit in 8 bits */
+
+ /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
+ Debug.Assert((flags & BTREE_UNORDERED) == 0 || (flags & BTREE_SINGLE) != 0);
+
+ /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
+ Debug.Assert((flags & BTREE_SINGLE) == 0 || isTempDb);
+
+ if ((db.flags & SQLITE_NoReadlock) != 0) {
+ flags |= BTREE_NO_READLOCK;
+ }
+ if (isMemdb) {
+ flags |= BTREE_MEMORY;
+ }
+ if ((vfsFlags & SQLITE_OPEN_MAIN_DB) != 0 && (isMemdb || isTempDb)) {
+ vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
+ }
+
+ p = new Btree();//sqlite3MallocZero(sizeof(Btree));
+ //if( !p ){
+ // return SQLITE_NOMEM;
+ //}
+ p.inTrans = TRANS_NONE;
+ p.db = db;
#if !SQLITE_OMIT_SHARED_CACHE
p.lock.pBtree = p;
p.lock.iTable = 1;
@@ -2137,79 +1976,72 @@ static int sqlite3BtreeOpen(
#endif
}
#endif
- if ( pBt == null )
- {
- /*
- ** The following asserts make sure that structures used by the btree are
- ** the right size. This is to guard against size changes that result
- ** when compiling on a different architecture.
- */
- Debug.Assert( sizeof( i64 ) == 8 || sizeof( i64 ) == 4 );
- Debug.Assert( sizeof( u64 ) == 8 || sizeof( u64 ) == 4 );
- Debug.Assert( sizeof( u32 ) == 4 );
- Debug.Assert( sizeof( u16 ) == 2 );
- Debug.Assert( sizeof( Pgno ) == 4 );
-
- pBt = new BtShared();//sqlite3MallocZero( sizeof(pBt) );
- //if( pBt==null ){
- // rc = SQLITE_NOMEM;
- // goto btree_open_out;
- //}
- rc = sqlite3PagerOpen( pVfs, out pBt.pPager, zFilename,
- EXTRA_SIZE, flags, vfsFlags, pageReinit );
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3PagerReadFileheader( pBt.pPager, zDbHeader.Length, zDbHeader );
- }
- if ( rc != SQLITE_OK )
- {
- goto btree_open_out;
- }
- pBt.openFlags = (u8)flags;
- pBt.db = db;
- sqlite3PagerSetBusyhandler( pBt.pPager, btreeInvokeBusyHandler, pBt );
- p.pBt = pBt;
-
- pBt.pCursor = null;
- pBt.pPage1 = null;
- pBt.readOnly = sqlite3PagerIsreadonly( pBt.pPager );
+ if (pBt == null) {
+ /*
+ ** The following asserts make sure that structures used by the btree are
+ ** the right size. This is to guard against size changes that result
+ ** when compiling on a different architecture.
+ */
+ Debug.Assert(sizeof(i64) == 8 || sizeof(i64) == 4);
+ Debug.Assert(sizeof(u64) == 8 || sizeof(u64) == 4);
+ Debug.Assert(sizeof(u32) == 4);
+ Debug.Assert(sizeof(u16) == 2);
+ Debug.Assert(sizeof(Pgno) == 4);
+
+ pBt = new BtShared();//sqlite3MallocZero( sizeof(pBt) );
+ //if( pBt==null ){
+ // rc = SQLITE_NOMEM;
+ // goto btree_open_out;
+ //}
+ rc = sqlite3PagerOpen(pVfs, out pBt.pPager, zFilename,
+ EXTRA_SIZE, flags, vfsFlags, pageReinit);
+ if (rc == SQLITE_OK) {
+ rc = sqlite3PagerReadFileheader(pBt.pPager, zDbHeader.Length, zDbHeader);
+ }
+ if (rc != SQLITE_OK) {
+ goto btree_open_out;
+ }
+ pBt.openFlags = (u8)flags;
+ pBt.db = db;
+ sqlite3PagerSetBusyhandler(pBt.pPager, btreeInvokeBusyHandler, pBt);
+ p.pBt = pBt;
+
+ pBt.pCursor = null;
+ pBt.pPage1 = null;
+ pBt.readOnly = sqlite3PagerIsreadonly(pBt.pPager);
#if SQLITE_SECURE_DELETE
pBt.secureDelete = true;
#endif
- pBt.pageSize = (u32)( ( zDbHeader[16] << 8 ) | ( zDbHeader[17] << 16 ) );
- if ( pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE
- || ( ( pBt.pageSize - 1 ) & pBt.pageSize ) != 0 )
- {
- pBt.pageSize = 0;
+ pBt.pageSize = (u32)((zDbHeader[16] << 8) | (zDbHeader[17] << 16));
+ if (pBt.pageSize < 512 || pBt.pageSize > SQLITE_MAX_PAGE_SIZE
+ || ((pBt.pageSize - 1) & pBt.pageSize) != 0) {
+ pBt.pageSize = 0;
#if !SQLITE_OMIT_AUTOVACUUM
- /* If the magic name ":memory:" will create an in-memory database, then
-** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
-** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
-** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
-** regular file-name. In this case the auto-vacuum applies as per normal.
-*/
- if ( zFilename != "" && !isMemdb )
- {
- pBt.autoVacuum = ( SQLITE_DEFAULT_AUTOVACUUM != 0 );
- pBt.incrVacuum = ( SQLITE_DEFAULT_AUTOVACUUM == 2 );
- }
+ /* If the magic name ":memory:" will create an in-memory database, then
+ ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
+ ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
+ ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
+ ** regular file-name. In this case the auto-vacuum applies as per normal.
+ */
+ if (zFilename != "" && !isMemdb) {
+ pBt.autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM != 0);
+ pBt.incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM == 2);
+ }
#endif
- nReserve = 0;
- }
- else
- {
- nReserve = zDbHeader[20];
- pBt.pageSizeFixed = true;
+ nReserve = 0;
+ } else {
+ nReserve = zDbHeader[20];
+ pBt.pageSizeFixed = true;
#if !SQLITE_OMIT_AUTOVACUUM
- pBt.autoVacuum = sqlite3Get4byte( zDbHeader, 36 + 4 * 4 ) != 0;
- pBt.incrVacuum = sqlite3Get4byte( zDbHeader, 36 + 7 * 4 ) != 0;
+ pBt.autoVacuum = sqlite3Get4byte(zDbHeader, 36 + 4 * 4) != 0;
+ pBt.incrVacuum = sqlite3Get4byte(zDbHeader, 36 + 7 * 4) != 0;
#endif
- }
- rc = sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, nReserve );
- if ( rc != 0 )
- goto btree_open_out;
- pBt.usableSize = (u16)( pBt.pageSize - nReserve );
- Debug.Assert( ( pBt.pageSize & 7 ) == 0 ); /* 8-byte alignment of pageSize */
+ }
+ rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, nReserve);
+ if (rc != 0)
+ goto btree_open_out;
+ pBt.usableSize = (u16)(pBt.pageSize - nReserve);
+ Debug.Assert((pBt.pageSize & 7) == 0); /* 8-byte alignment of pageSize */
#if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO)
/* Add the new BtShared object to the linked list sharable BtShareds.
@@ -2232,7 +2064,7 @@ static int sqlite3BtreeOpen(
sqlite3_mutex_leave(mutexShared);
}
#endif
- }
+ }
#if !(SQLITE_OMIT_SHARED_CACHE) && !(SQLITE_OMIT_DISKIO)
/* If the new Btree uses a sharable pBtShared, then link the new
@@ -2265,47 +2097,40 @@ static int sqlite3BtreeOpen(
}
}
#endif
- ppBtree = p;
-
-btree_open_out:
- if ( rc != SQLITE_OK )
- {
- if ( pBt != null && pBt.pPager != null )
- {
- sqlite3PagerClose( pBt.pPager );
- }
- pBt = null; // sqlite3_free(ref pBt);
- p = null; // sqlite3_free(ref p);
- ppBtree = null;
- }
- else
- {
- /* If the B-Tree was successfully opened, set the pager-cache size to the
- ** default value. Except, when opening on an existing shared pager-cache,
- ** do not change the pager-cache size.
- */
- if ( sqlite3BtreeSchema( p, 0, null ) == null )
- {
- sqlite3PagerSetCachesize( p.pBt.pPager, SQLITE_DEFAULT_CACHE_SIZE );
- }
+ ppBtree = p;
+
+ btree_open_out:
+ if (rc != SQLITE_OK) {
+ if (pBt != null && pBt.pPager != null) {
+ sqlite3PagerClose(pBt.pPager);
+ }
+ pBt = null; // sqlite3_free(ref pBt);
+ p = null; // sqlite3_free(ref p);
+ ppBtree = null;
+ } else {
+ /* If the B-Tree was successfully opened, set the pager-cache size to the
+ ** default value. Except, when opening on an existing shared pager-cache,
+ ** do not change the pager-cache size.
+ */
+ if (sqlite3BtreeSchema(p, 0, null) == null) {
+ sqlite3PagerSetCachesize(p.pBt.pPager, SQLITE_DEFAULT_CACHE_SIZE);
+ }
- }
- if ( mutexOpen != null )
- {
- Debug.Assert( sqlite3_mutex_held( mutexOpen ) );
- sqlite3_mutex_leave( mutexOpen );
- }
- return rc;
-}
+ }
+ if (mutexOpen != null) {
+ Debug.Assert(sqlite3_mutex_held(mutexOpen));
+ sqlite3_mutex_leave(mutexOpen);
+ }
+ return rc;
+ }
-/*
-** Decrement the BtShared.nRef counter. When it reaches zero,
-** remove the BtShared structure from the sharing list. Return
-** true if the BtShared.nRef counter reaches zero and return
-** false if it is still positive.
-*/
-static bool removeFromSharingList( BtShared pBt )
-{
+ /*
+ ** Decrement the BtShared.nRef counter. When it reaches zero,
+ ** remove the BtShared structure from the sharing list. Return
+ ** true if the BtShared.nRef counter reaches zero and return
+ ** false if it is still positive.
+ */
+ static bool removeFromSharingList(BtShared pBt) {
#if !SQLITE_OMIT_SHARED_CACHE
sqlite3_mutex pMaster;
BtShared pList;
@@ -2335,81 +2160,73 @@ static bool removeFromSharingList( BtShared pBt )
sqlite3_mutex_leave(pMaster);
return removed;
#else
- return true;
+ return true;
#endif
-}
+ }
-/*
-** Make sure pBt.pTmpSpace points to an allocation of
-** MX_CELL_SIZE(pBt) bytes.
-*/
-static void allocateTempSpace( BtShared pBt )
-{
- if ( null == pBt.pTmpSpace )
- {
- pBt.pTmpSpace = sqlite3Malloc( pBt.pageSize );
- }
-}
+ /*
+ ** Make sure pBt.pTmpSpace points to an allocation of
+ ** MX_CELL_SIZE(pBt) bytes.
+ */
+ static void allocateTempSpace(BtShared pBt) {
+ if (null == pBt.pTmpSpace) {
+ pBt.pTmpSpace = sqlite3Malloc(pBt.pageSize);
+ }
+ }
-/*
-** Free the pBt.pTmpSpace allocation
-*/
-static void freeTempSpace( BtShared pBt )
-{
- sqlite3PageFree( ref pBt.pTmpSpace );
-}
+ /*
+ ** Free the pBt.pTmpSpace allocation
+ */
+ static void freeTempSpace(BtShared pBt) {
+ sqlite3PageFree(ref pBt.pTmpSpace);
+ }
-/*
-** Close an open database and invalidate all cursors.
-*/
-static int sqlite3BtreeClose( ref Btree p )
-{
- BtShared pBt = p.pBt;
- BtCursor pCur;
-
- /* Close all cursors opened via this handle. */
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- sqlite3BtreeEnter( p );
- pCur = pBt.pCursor;
- while ( pCur != null )
- {
- BtCursor pTmp = pCur;
- pCur = pCur.pNext;
- if ( pTmp.pBtree == p )
- {
- sqlite3BtreeCloseCursor( pTmp );
- }
- }
-
- /* Rollback any active transaction and free the handle structure.
- ** The call to sqlite3BtreeRollback() drops any table-locks held by
- ** this handle.
- */
- sqlite3BtreeRollback( p );
- sqlite3BtreeLeave( p );
-
- /* If there are still other outstanding references to the shared-btree
- ** structure, return now. The remainder of this procedure cleans
- ** up the shared-btree.
- */
- Debug.Assert( p.wantToLock == 0 && !p.locked );
- if ( !p.sharable || removeFromSharingList( pBt ) )
- {
- /* The pBt is no longer on the sharing list, so we can access
- ** it without having to hold the mutex.
- **
- ** Clean out and delete the BtShared object.
- */
- Debug.Assert( null == pBt.pCursor );
- sqlite3PagerClose( pBt.pPager );
- if ( pBt.xFreeSchema != null && pBt.pSchema != null )
- {
- pBt.xFreeSchema( pBt.pSchema );
- }
- pBt.pSchema = null;// sqlite3DbFree(0, pBt->pSchema);
- //freeTempSpace(pBt);
- pBt = null; //sqlite3_free(ref pBt);
- }
+ /*
+ ** Close an open database and invalidate all cursors.
+ */
+ static int sqlite3BtreeClose(ref Btree p) {
+ BtShared pBt = p.pBt;
+ BtCursor pCur;
+
+ /* Close all cursors opened via this handle. */
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ sqlite3BtreeEnter(p);
+ pCur = pBt.pCursor;
+ while (pCur != null) {
+ BtCursor pTmp = pCur;
+ pCur = pCur.pNext;
+ if (pTmp.pBtree == p) {
+ sqlite3BtreeCloseCursor(pTmp);
+ }
+ }
+
+ /* Rollback any active transaction and free the handle structure.
+ ** The call to sqlite3BtreeRollback() drops any table-locks held by
+ ** this handle.
+ */
+ sqlite3BtreeRollback(p);
+ sqlite3BtreeLeave(p);
+
+ /* If there are still other outstanding references to the shared-btree
+ ** structure, return now. The remainder of this procedure cleans
+ ** up the shared-btree.
+ */
+ Debug.Assert(p.wantToLock == 0 && !p.locked);
+ if (!p.sharable || removeFromSharingList(pBt)) {
+ /* The pBt is no longer on the sharing list, so we can access
+ ** it without having to hold the mutex.
+ **
+ ** Clean out and delete the BtShared object.
+ */
+ Debug.Assert(null == pBt.pCursor);
+ sqlite3PagerClose(pBt.pPager);
+ if (pBt.xFreeSchema != null && pBt.pSchema != null) {
+ pBt.xFreeSchema(pBt.pSchema);
+ }
+ pBt.pSchema = null;// sqlite3DbFree(0, pBt->pSchema);
+ //freeTempSpace(pBt);
+ pBt = null; //sqlite3_free(ref pBt);
+ }
#if !SQLITE_OMIT_SHARED_CACHE
Debug.Assert( p.wantToLock==null );
@@ -2418,295 +2235,273 @@ static int sqlite3BtreeClose( ref Btree p )
if( p.pNext ) p.pNext.pPrev = p.pPrev;
#endif
- //sqlite3_free(ref p);
- return SQLITE_OK;
-}
-
-/*
-** Change the limit on the number of pages allowed in the cache.
-**
-** The maximum number of cache pages is set to the absolute
-** value of mxPage. If mxPage is negative, the pager will
-** operate asynchronously - it will not stop to do fsync()s
-** to insure data is written to the disk surface before
-** continuing. Transactions still work if synchronous is off,
-** and the database cannot be corrupted if this program
-** crashes. But if the operating system crashes or there is
-** an abrupt power failure when synchronous is off, the database
-** could be left in an inconsistent and unrecoverable state.
-** Synchronous is on by default so database corruption is not
-** normally a worry.
-*/
-static int sqlite3BtreeSetCacheSize( Btree p, int mxPage )
-{
- BtShared pBt = p.pBt;
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- sqlite3BtreeEnter( p );
- sqlite3PagerSetCachesize( pBt.pPager, mxPage );
- sqlite3BtreeLeave( p );
- return SQLITE_OK;
-}
+ //sqlite3_free(ref p);
+ return SQLITE_OK;
+ }
-/*
-** Change the way data is synced to disk in order to increase or decrease
-** how well the database resists damage due to OS crashes and power
-** failures. Level 1 is the same as asynchronous (no syncs() occur and
-** there is a high probability of damage) Level 2 is the default. There
-** is a very low but non-zero probability of damage. Level 3 reduces the
-** probability of damage to near zero but with a write performance reduction.
-*/
+ /*
+ ** Change the limit on the number of pages allowed in the cache.
+ **
+ ** The maximum number of cache pages is set to the absolute
+ ** value of mxPage. If mxPage is negative, the pager will
+ ** operate asynchronously - it will not stop to do fsync()s
+ ** to insure data is written to the disk surface before
+ ** continuing. Transactions still work if synchronous is off,
+ ** and the database cannot be corrupted if this program
+ ** crashes. But if the operating system crashes or there is
+ ** an abrupt power failure when synchronous is off, the database
+ ** could be left in an inconsistent and unrecoverable state.
+ ** Synchronous is on by default so database corruption is not
+ ** normally a worry.
+ */
+ static int sqlite3BtreeSetCacheSize(Btree p, int mxPage) {
+ BtShared pBt = p.pBt;
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ sqlite3BtreeEnter(p);
+ sqlite3PagerSetCachesize(pBt.pPager, mxPage);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+ }
+
+ /*
+ ** Change the way data is synced to disk in order to increase or decrease
+ ** how well the database resists damage due to OS crashes and power
+ ** failures. Level 1 is the same as asynchronous (no syncs() occur and
+ ** there is a high probability of damage) Level 2 is the default. There
+ ** is a very low but non-zero probability of damage. Level 3 reduces the
+ ** probability of damage to near zero but with a write performance reduction.
+ */
#if !SQLITE_OMIT_PAGER_PRAGMAS
-static int sqlite3BtreeSetSafetyLevel(
-Btree p, /* The btree to set the safety level on */
-int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
-int fullSync, /* PRAGMA fullfsync. */
-int ckptFullSync /* PRAGMA checkpoint_fullfync */
-)
-{
- BtShared pBt = p.pBt;
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- Debug.Assert( level >= 1 && level <= 3 );
- sqlite3BtreeEnter( p );
- sqlite3PagerSetSafetyLevel( pBt.pPager, level, fullSync, ckptFullSync );
- sqlite3BtreeLeave( p );
- return SQLITE_OK;
-}
+ static int sqlite3BtreeSetSafetyLevel(
+ Btree p, /* The btree to set the safety level on */
+ int level, /* PRAGMA synchronous. 1=OFF, 2=NORMAL, 3=FULL */
+ int fullSync, /* PRAGMA fullfsync. */
+ int ckptFullSync /* PRAGMA checkpoint_fullfync */
+ ) {
+ BtShared pBt = p.pBt;
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ Debug.Assert(level >= 1 && level <= 3);
+ sqlite3BtreeEnter(p);
+ sqlite3PagerSetSafetyLevel(pBt.pPager, level, fullSync, ckptFullSync);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+ }
#endif
-/*
-** Return TRUE if the given btree is set to safety level 1. In other
-** words, return TRUE if no sync() occurs on the disk files.
-*/
-static int sqlite3BtreeSyncDisabled( Btree p )
-{
- BtShared pBt = p.pBt;
- int rc;
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- sqlite3BtreeEnter( p );
- Debug.Assert( pBt != null && pBt.pPager != null );
- rc = sqlite3PagerNosync( pBt.pPager ) ? 1 : 0;
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** Return TRUE if the given btree is set to safety level 1. In other
+ ** words, return TRUE if no sync() occurs on the disk files.
+ */
+ static int sqlite3BtreeSyncDisabled(Btree p) {
+ BtShared pBt = p.pBt;
+ int rc;
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ sqlite3BtreeEnter(p);
+ Debug.Assert(pBt != null && pBt.pPager != null);
+ rc = sqlite3PagerNosync(pBt.pPager) ? 1 : 0;
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** Change the default pages size and the number of reserved bytes per page.
-** Or, if the page size has already been fixed, return SQLITE_READONLY
-** without changing anything.
-**
-** The page size must be a power of 2 between 512 and 65536. If the page
-** size supplied does not meet this constraint then the page size is not
-** changed.
-**
-** Page sizes are constrained to be a power of two so that the region
-** of the database file used for locking (beginning at PENDING_BYTE,
-** the first byte past the 1GB boundary, 0x40000000) needs to occur
-** at the beginning of a page.
-**
-** If parameter nReserve is less than zero, then the number of reserved
-** bytes per page is left unchanged.
-**
-** If iFix!=0 then the pageSizeFixed flag is set so that the page size
-** and autovacuum mode can no longer be changed.
-*/
-static int sqlite3BtreeSetPageSize( Btree p, int pageSize, int nReserve, int iFix )
-{
- int rc = SQLITE_OK;
- BtShared pBt = p.pBt;
- Debug.Assert( nReserve >= -1 && nReserve <= 255 );
- sqlite3BtreeEnter( p );
- if ( pBt.pageSizeFixed )
- {
- sqlite3BtreeLeave( p );
- return SQLITE_READONLY;
- }
- if ( nReserve < 0 )
- {
- nReserve = (int)( pBt.pageSize - pBt.usableSize );
- }
- Debug.Assert( nReserve >= 0 && nReserve <= 255 );
- if ( pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE &&
- ( ( pageSize - 1 ) & pageSize ) == 0 )
- {
- Debug.Assert( ( pageSize & 7 ) == 0 );
- Debug.Assert( null == pBt.pPage1 && null == pBt.pCursor );
- pBt.pageSize = (u32)pageSize;
- // freeTempSpace(pBt);
- }
- rc = sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize, nReserve );
- pBt.usableSize = (u16)( pBt.pageSize - nReserve );
- if ( iFix != 0 )
- pBt.pageSizeFixed = true;
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** Change the default pages size and the number of reserved bytes per page.
+ ** Or, if the page size has already been fixed, return SQLITE_READONLY
+ ** without changing anything.
+ **
+ ** The page size must be a power of 2 between 512 and 65536. If the page
+ ** size supplied does not meet this constraint then the page size is not
+ ** changed.
+ **
+ ** Page sizes are constrained to be a power of two so that the region
+ ** of the database file used for locking (beginning at PENDING_BYTE,
+ ** the first byte past the 1GB boundary, 0x40000000) needs to occur
+ ** at the beginning of a page.
+ **
+ ** If parameter nReserve is less than zero, then the number of reserved
+ ** bytes per page is left unchanged.
+ **
+ ** If iFix!=0 then the pageSizeFixed flag is set so that the page size
+ ** and autovacuum mode can no longer be changed.
+ */
+ static int sqlite3BtreeSetPageSize(Btree p, int pageSize, int nReserve, int iFix) {
+ int rc = SQLITE_OK;
+ BtShared pBt = p.pBt;
+ Debug.Assert(nReserve >= -1 && nReserve <= 255);
+ sqlite3BtreeEnter(p);
+ if (pBt.pageSizeFixed) {
+ sqlite3BtreeLeave(p);
+ return SQLITE_READONLY;
+ }
+ if (nReserve < 0) {
+ nReserve = (int)(pBt.pageSize - pBt.usableSize);
+ }
+ Debug.Assert(nReserve >= 0 && nReserve <= 255);
+ if (pageSize >= 512 && pageSize <= SQLITE_MAX_PAGE_SIZE &&
+ ((pageSize - 1) & pageSize) == 0) {
+ Debug.Assert((pageSize & 7) == 0);
+ Debug.Assert(null == pBt.pPage1 && null == pBt.pCursor);
+ pBt.pageSize = (u32)pageSize;
+ // freeTempSpace(pBt);
+ }
+ rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize, nReserve);
+ pBt.usableSize = (u16)(pBt.pageSize - nReserve);
+ if (iFix != 0)
+ pBt.pageSizeFixed = true;
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** Return the currently defined page size
-*/
-static int sqlite3BtreeGetPageSize( Btree p )
-{
- return (int)p.pBt.pageSize;
-}
+ /*
+ ** Return the currently defined page size
+ */
+ static int sqlite3BtreeGetPageSize(Btree p) {
+ return (int)p.pBt.pageSize;
+ }
#if !(SQLITE_OMIT_PAGER_PRAGMAS) || !(SQLITE_OMIT_VACUUM)
-/*
-** Return the number of bytes of space at the end of every page that
-** are intentually left unused. This is the "reserved" space that is
-** sometimes used by extensions.
-*/
-static int sqlite3BtreeGetReserve( Btree p )
-{
- int n;
- sqlite3BtreeEnter( p );
- n = (int)( p.pBt.pageSize - p.pBt.usableSize );
- sqlite3BtreeLeave( p );
- return n;
-}
+ /*
+ ** Return the number of bytes of space at the end of every page that
+ ** are intentually left unused. This is the "reserved" space that is
+ ** sometimes used by extensions.
+ */
+ static int sqlite3BtreeGetReserve(Btree p) {
+ int n;
+ sqlite3BtreeEnter(p);
+ n = (int)(p.pBt.pageSize - p.pBt.usableSize);
+ sqlite3BtreeLeave(p);
+ return n;
+ }
-/*
-** Set the maximum page count for a database if mxPage is positive.
-** No changes are made if mxPage is 0 or negative.
-** Regardless of the value of mxPage, return the maximum page count.
-*/
-static Pgno sqlite3BtreeMaxPageCount( Btree p, int mxPage )
-{
- Pgno n;
- sqlite3BtreeEnter( p );
- n = sqlite3PagerMaxPageCount( p.pBt.pPager, mxPage );
- sqlite3BtreeLeave( p );
- return n;
-}
+ /*
+ ** Set the maximum page count for a database if mxPage is positive.
+ ** No changes are made if mxPage is 0 or negative.
+ ** Regardless of the value of mxPage, return the maximum page count.
+ */
+ static Pgno sqlite3BtreeMaxPageCount(Btree p, int mxPage) {
+ Pgno n;
+ sqlite3BtreeEnter(p);
+ n = sqlite3PagerMaxPageCount(p.pBt.pPager, mxPage);
+ sqlite3BtreeLeave(p);
+ return n;
+ }
-/*
-** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
-** then make no changes. Always return the value of the secureDelete
-** setting after the change.
-*/
-static int sqlite3BtreeSecureDelete( Btree p, int newFlag )
-{
- int b;
- if ( p == null )
- return 0;
- sqlite3BtreeEnter( p );
- if ( newFlag >= 0 )
- {
- p.pBt.secureDelete = ( newFlag != 0 );
- }
- b = p.pBt.secureDelete ? 1 : 0;
- sqlite3BtreeLeave( p );
- return b;
-}
+ /*
+ ** Set the secureDelete flag if newFlag is 0 or 1. If newFlag is -1,
+ ** then make no changes. Always return the value of the secureDelete
+ ** setting after the change.
+ */
+ static int sqlite3BtreeSecureDelete(Btree p, int newFlag) {
+ int b;
+ if (p == null)
+ return 0;
+ sqlite3BtreeEnter(p);
+ if (newFlag >= 0) {
+ p.pBt.secureDelete = (newFlag != 0);
+ }
+ b = p.pBt.secureDelete ? 1 : 0;
+ sqlite3BtreeLeave(p);
+ return b;
+ }
#endif //* !(SQLITE_OMIT_PAGER_PRAGMAS) || !(SQLITE_OMIT_VACUUM) */
-/*
-** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
-** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
-** is disabled. The default value for the auto-vacuum property is
-** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
-*/
-static int sqlite3BtreeSetAutoVacuum( Btree p, int autoVacuum )
-{
+ /*
+ ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
+ ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
+ ** is disabled. The default value for the auto-vacuum property is
+ ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
+ */
+ static int sqlite3BtreeSetAutoVacuum(Btree p, int autoVacuum) {
#if SQLITE_OMIT_AUTOVACUUM
return SQLITE_READONLY;
#else
- BtShared pBt = p.pBt;
- int rc = SQLITE_OK;
- u8 av = (u8)autoVacuum;
-
- sqlite3BtreeEnter( p );
- if ( pBt.pageSizeFixed && ( av != 0 ) != pBt.autoVacuum )
- {
- rc = SQLITE_READONLY;
- }
- else
- {
- pBt.autoVacuum = av != 0;
- pBt.incrVacuum = av == 2;
- }
- sqlite3BtreeLeave( p );
- return rc;
+ BtShared pBt = p.pBt;
+ int rc = SQLITE_OK;
+ u8 av = (u8)autoVacuum;
+
+ sqlite3BtreeEnter(p);
+ if (pBt.pageSizeFixed && (av != 0) != pBt.autoVacuum) {
+ rc = SQLITE_READONLY;
+ } else {
+ pBt.autoVacuum = av != 0;
+ pBt.incrVacuum = av == 2;
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
#endif
-}
+ }
-/*
-** Return the value of the 'auto-vacuum' property. If auto-vacuum is
-** enabled 1 is returned. Otherwise 0.
-*/
-static int sqlite3BtreeGetAutoVacuum( Btree p )
-{
+ /*
+ ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
+ ** enabled 1 is returned. Otherwise 0.
+ */
+ static int sqlite3BtreeGetAutoVacuum(Btree p) {
#if SQLITE_OMIT_AUTOVACUUM
return BTREE_AUTOVACUUM_NONE;
#else
- int rc;
- sqlite3BtreeEnter( p );
- rc = (
- ( !p.pBt.autoVacuum ) ? BTREE_AUTOVACUUM_NONE :
- ( !p.pBt.incrVacuum ) ? BTREE_AUTOVACUUM_FULL :
- BTREE_AUTOVACUUM_INCR
- );
- sqlite3BtreeLeave( p );
- return rc;
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = (
+ (!p.pBt.autoVacuum) ? BTREE_AUTOVACUUM_NONE :
+ (!p.pBt.incrVacuum) ? BTREE_AUTOVACUUM_FULL :
+ BTREE_AUTOVACUUM_INCR
+ );
+ sqlite3BtreeLeave(p);
+ return rc;
#endif
-}
+ }
-/*
-** Get a reference to pPage1 of the database file. This will
-** also acquire a readlock on that file.
-**
-** SQLITE_OK is returned on success. If the file is not a
-** well-formed database file, then SQLITE_CORRUPT is returned.
-** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
-** is returned if we run out of memory.
-*/
-static int lockBtree( BtShared pBt )
-{
- int rc; /* Result code from subfunctions */
- MemPage pPage1 = null; /* Page 1 of the database file */
- Pgno nPage; /* Number of pages in the database */
- Pgno nPageFile = 0; /* Number of pages in the database file */
- ////Pgno nPageHeader; /* Number of pages in the database according to hdr */
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( pBt.pPage1 == null );
- rc = sqlite3PagerSharedLock( pBt.pPager );
- if ( rc != SQLITE_OK )
- return rc;
- rc = btreeGetPage( pBt, 1, ref pPage1, 0 );
- if ( rc != SQLITE_OK )
- return rc;
-
- /* Do some checking to help insure the file we opened really is
- ** a valid database file.
- */
- nPage = sqlite3Get4byte( pPage1.aData, 28 );//get4byte(28+(u8*)pPage1->aData);
- sqlite3PagerPagecount( pBt.pPager, out nPageFile );
- if ( nPage == 0 || memcmp( pPage1.aData, 24, pPage1.aData, 92, 4 ) != 0 )//memcmp(24 + (u8*)pPage1.aData, 92 + (u8*)pPage1.aData, 4) != 0)
- {
- nPage = nPageFile;
- }
- if ( nPage > 0 )
- {
- u32 pageSize;
- u32 usableSize;
- u8[] page1 = pPage1.aData;
- rc = SQLITE_NOTADB;
- if ( memcmp( page1, zMagicHeader, 16 ) != 0 )
- {
- goto page1_init_failed;
- }
+ /*
+ ** Get a reference to pPage1 of the database file. This will
+ ** also acquire a readlock on that file.
+ **
+ ** SQLITE_OK is returned on success. If the file is not a
+ ** well-formed database file, then SQLITE_CORRUPT is returned.
+ ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
+ ** is returned if we run out of memory.
+ */
+ static int lockBtree(BtShared pBt) {
+ int rc; /* Result code from subfunctions */
+ MemPage pPage1 = null; /* Page 1 of the database file */
+ Pgno nPage; /* Number of pages in the database */
+ Pgno nPageFile = 0; /* Number of pages in the database file */
+ ////Pgno nPageHeader; /* Number of pages in the database according to hdr */
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(pBt.pPage1 == null);
+ rc = sqlite3PagerSharedLock(pBt.pPager);
+ if (rc != SQLITE_OK)
+ return rc;
+ rc = btreeGetPage(pBt, 1, ref pPage1, 0);
+ if (rc != SQLITE_OK)
+ return rc;
+
+ /* Do some checking to help insure the file we opened really is
+ ** a valid database file.
+ */
+ nPage = sqlite3Get4byte(pPage1.aData, 28);//get4byte(28+(u8*)pPage1->aData);
+ sqlite3PagerPagecount(pBt.pPager, out nPageFile);
+ if (nPage == 0 || memcmp(pPage1.aData, 24, pPage1.aData, 92, 4) != 0)//memcmp(24 + (u8*)pPage1.aData, 92 + (u8*)pPage1.aData, 4) != 0)
+ {
+ nPage = nPageFile;
+ }
+ if (nPage > 0) {
+ u32 pageSize;
+ u32 usableSize;
+ u8[] page1 = pPage1.aData;
+ rc = SQLITE_NOTADB;
+ if (memcmp(page1, zMagicHeader, 16) != 0) {
+ goto page1_init_failed;
+ }
#if SQLITE_OMIT_WAL
- if ( page1[18] > 1 )
- {
- pBt.readOnly = true;
- }
- if ( page1[19] > 1 )
- {
- pBt.pSchema.file_format = page1[19];
- goto page1_init_failed;
- }
+ if (page1[18] > 1) {
+ pBt.readOnly = true;
+ }
+ if (page1[19] > 1) {
+ pBt.pSchema.file_format = page1[19];
+ goto page1_init_failed;
+ }
#else
if( page1[18]>2 ){
pBt.readOnly = true;
@@ -2736,212 +2531,201 @@ static int lockBtree( BtShared pBt )
}
#endif
- /* The maximum embedded fraction must be exactly 25%. And the minimum
-** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
-** The original design allowed these amounts to vary, but as of
-** version 3.6.0, we require them to be fixed.
-*/
- if ( memcmp( page1, 21, "\x0040\x0020\x0020", 3 ) != 0 )// "\100\040\040"
- {
- goto page1_init_failed;
- }
- pageSize = (u32)( ( page1[16] << 8 ) | ( page1[17] << 16 ) );
- if ( ( ( pageSize - 1 ) & pageSize ) != 0
- || pageSize > SQLITE_MAX_PAGE_SIZE
- || pageSize <= 256
- )
- {
- goto page1_init_failed;
- }
- Debug.Assert( ( pageSize & 7 ) == 0 );
- usableSize = pageSize - page1[20];
- if ( pageSize != pBt.pageSize )
- {
- /* After reading the first page of the database assuming a page size
- ** of BtShared.pageSize, we have discovered that the page-size is
- ** actually pageSize. Unlock the database, leave pBt.pPage1 at
- ** zero and return SQLITE_OK. The caller will call this function
- ** again with the correct page-size.
- */
- releasePage( pPage1 );
- pBt.usableSize = usableSize;
- pBt.pageSize = pageSize;
- // freeTempSpace(pBt);
- rc = sqlite3PagerSetPagesize( pBt.pPager, ref pBt.pageSize,
- (int)( pageSize - usableSize ) );
- return rc;
- }
- if ( ( pBt.db.flags & SQLITE_RecoveryMode ) == 0 && nPage > nPageFile )
- {
- rc = SQLITE_CORRUPT_BKPT();
- goto page1_init_failed;
- }
- if ( usableSize < 480 )
- {
- goto page1_init_failed;
- }
- pBt.pageSize = pageSize;
- pBt.usableSize = usableSize;
+ /* The maximum embedded fraction must be exactly 25%. And the minimum
+ ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
+ ** The original design allowed these amounts to vary, but as of
+ ** version 3.6.0, we require them to be fixed.
+ */
+ if (memcmp(page1, 21, "\x0040\x0020\x0020", 3) != 0)// "\100\040\040"
+ {
+ goto page1_init_failed;
+ }
+ pageSize = (u32)((page1[16] << 8) | (page1[17] << 16));
+ if (((pageSize - 1) & pageSize) != 0
+ || pageSize > SQLITE_MAX_PAGE_SIZE
+ || pageSize <= 256
+ ) {
+ goto page1_init_failed;
+ }
+ Debug.Assert((pageSize & 7) == 0);
+ usableSize = pageSize - page1[20];
+ if (pageSize != pBt.pageSize) {
+ /* After reading the first page of the database assuming a page size
+ ** of BtShared.pageSize, we have discovered that the page-size is
+ ** actually pageSize. Unlock the database, leave pBt.pPage1 at
+ ** zero and return SQLITE_OK. The caller will call this function
+ ** again with the correct page-size.
+ */
+ releasePage(pPage1);
+ pBt.usableSize = usableSize;
+ pBt.pageSize = pageSize;
+ // freeTempSpace(pBt);
+ rc = sqlite3PagerSetPagesize(pBt.pPager, ref pBt.pageSize,
+ (int)(pageSize - usableSize));
+ return rc;
+ }
+ if ((pBt.db.flags & SQLITE_RecoveryMode) == 0 && nPage > nPageFile) {
+ rc = SQLITE_CORRUPT_BKPT();
+ goto page1_init_failed;
+ }
+ if (usableSize < 480) {
+ goto page1_init_failed;
+ }
+ pBt.pageSize = pageSize;
+ pBt.usableSize = usableSize;
#if !SQLITE_OMIT_AUTOVACUUM
- pBt.autoVacuum = ( sqlite3Get4byte( page1, 36 + 4 * 4 ) != 0 );
- pBt.incrVacuum = ( sqlite3Get4byte( page1, 36 + 7 * 4 ) != 0 );
+ pBt.autoVacuum = (sqlite3Get4byte(page1, 36 + 4 * 4) != 0);
+ pBt.incrVacuum = (sqlite3Get4byte(page1, 36 + 7 * 4) != 0);
#endif
- }
-
- /* maxLocal is the maximum amount of payload to store locally for
- ** a cell. Make sure it is small enough so that at least minFanout
- ** cells can will fit on one page. We assume a 10-byte page header.
- ** Besides the payload, the cell must store:
- ** 2-byte pointer to the cell
- ** 4-byte child pointer
- ** 9-byte nKey value
- ** 4-byte nData value
- ** 4-byte overflow page pointer
- ** So a cell consists of a 2-byte pointer, a header which is as much as
- ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
- ** page pointer.
- */
- pBt.maxLocal = (u16)( ( pBt.usableSize - 12 ) * 64 / 255 - 23 );
- pBt.minLocal = (u16)( ( pBt.usableSize - 12 ) * 32 / 255 - 23 );
- pBt.maxLeaf = (u16)( pBt.usableSize - 35 );
- pBt.minLeaf = (u16)( ( pBt.usableSize - 12 ) * 32 / 255 - 23 );
- Debug.Assert( pBt.maxLeaf + 23 <= MX_CELL_SIZE( pBt ) );
- pBt.pPage1 = pPage1;
- pBt.nPage = nPage;
- return SQLITE_OK;
-
-page1_init_failed:
- releasePage( pPage1 );
- pBt.pPage1 = null;
- return rc;
-}
+ }
-/*
-** If there are no outstanding cursors and we are not in the middle
-** of a transaction but there is a read lock on the database, then
-** this routine unrefs the first page of the database file which
-** has the effect of releasing the read lock.
-**
-** If there is a transaction in progress, this routine is a no-op.
-*/
-static void unlockBtreeIfUnused( BtShared pBt )
-{
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( pBt.pCursor == null || pBt.inTransaction > TRANS_NONE );
- if ( pBt.inTransaction == TRANS_NONE && pBt.pPage1 != null )
- {
- Debug.Assert( pBt.pPage1.aData != null );
- //Debug.Assert( sqlite3PagerRefcount( pBt.pPager ) == 1 );
- releasePage( pBt.pPage1 );
- pBt.pPage1 = null;
- }
-}
+ /* maxLocal is the maximum amount of payload to store locally for
+ ** a cell. Make sure it is small enough so that at least minFanout
+ ** cells can will fit on one page. We assume a 10-byte page header.
+ ** Besides the payload, the cell must store:
+ ** 2-byte pointer to the cell
+ ** 4-byte child pointer
+ ** 9-byte nKey value
+ ** 4-byte nData value
+ ** 4-byte overflow page pointer
+ ** So a cell consists of a 2-byte pointer, a header which is as much as
+ ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
+ ** page pointer.
+ */
+ pBt.maxLocal = (u16)((pBt.usableSize - 12) * 64 / 255 - 23);
+ pBt.minLocal = (u16)((pBt.usableSize - 12) * 32 / 255 - 23);
+ pBt.maxLeaf = (u16)(pBt.usableSize - 35);
+ pBt.minLeaf = (u16)((pBt.usableSize - 12) * 32 / 255 - 23);
+ Debug.Assert(pBt.maxLeaf + 23 <= MX_CELL_SIZE(pBt));
+ pBt.pPage1 = pPage1;
+ pBt.nPage = nPage;
+ return SQLITE_OK;
+
+ page1_init_failed:
+ releasePage(pPage1);
+ pBt.pPage1 = null;
+ return rc;
+ }
-/*
-** If pBt points to an empty file then convert that empty file
-** into a new empty database by initializing the first page of
-** the database.
-*/
-static int newDatabase( BtShared pBt )
-{
- MemPage pP1;
- byte[] data;
- int rc;
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- if ( pBt.nPage > 0 )
- {
- return SQLITE_OK;
- }
- pP1 = pBt.pPage1;
- Debug.Assert( pP1 != null );
- data = pP1.aData;
- rc = sqlite3PagerWrite( pP1.pDbPage );
- if ( rc != 0 )
- return rc;
- Buffer.BlockCopy( zMagicHeader, 0, data, 0, 16 );// memcpy(data, zMagicHeader, sizeof(zMagicHeader));
- Debug.Assert( zMagicHeader.Length == 16 );
- data[16] = (u8)( ( pBt.pageSize >> 8 ) & 0xff );
- data[17] = (u8)( ( pBt.pageSize >> 16 ) & 0xff );
- data[18] = 1;
- data[19] = 1;
- Debug.Assert( pBt.usableSize <= pBt.pageSize && pBt.usableSize + 255 >= pBt.pageSize );
- data[20] = (u8)( pBt.pageSize - pBt.usableSize );
- data[21] = 64;
- data[22] = 32;
- data[23] = 32;
- //memset(&data[24], 0, 100-24);
- zeroPage( pP1, PTF_INTKEY | PTF_LEAF | PTF_LEAFDATA );
- pBt.pageSizeFixed = true;
+ /*
+ ** If there are no outstanding cursors and we are not in the middle
+ ** of a transaction but there is a read lock on the database, then
+ ** this routine unrefs the first page of the database file which
+ ** has the effect of releasing the read lock.
+ **
+ ** If there is a transaction in progress, this routine is a no-op.
+ */
+ static void unlockBtreeIfUnused(BtShared pBt) {
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(pBt.pCursor == null || pBt.inTransaction > TRANS_NONE);
+ if (pBt.inTransaction == TRANS_NONE && pBt.pPage1 != null) {
+ Debug.Assert(pBt.pPage1.aData != null);
+ //Debug.Assert( sqlite3PagerRefcount( pBt.pPager ) == 1 );
+ releasePage(pBt.pPage1);
+ pBt.pPage1 = null;
+ }
+ }
+
+ /*
+ ** If pBt points to an empty file then convert that empty file
+ ** into a new empty database by initializing the first page of
+ ** the database.
+ */
+ static int newDatabase(BtShared pBt) {
+ MemPage pP1;
+ byte[] data;
+ int rc;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ if (pBt.nPage > 0) {
+ return SQLITE_OK;
+ }
+ pP1 = pBt.pPage1;
+ Debug.Assert(pP1 != null);
+ data = pP1.aData;
+ rc = sqlite3PagerWrite(pP1.pDbPage);
+ if (rc != 0)
+ return rc;
+ Buffer.BlockCopy(zMagicHeader, 0, data, 0, 16);// memcpy(data, zMagicHeader, sizeof(zMagicHeader));
+ Debug.Assert(zMagicHeader.Length == 16);
+ data[16] = (u8)((pBt.pageSize >> 8) & 0xff);
+ data[17] = (u8)((pBt.pageSize >> 16) & 0xff);
+ data[18] = 1;
+ data[19] = 1;
+ Debug.Assert(pBt.usableSize <= pBt.pageSize && pBt.usableSize + 255 >= pBt.pageSize);
+ data[20] = (u8)(pBt.pageSize - pBt.usableSize);
+ data[21] = 64;
+ data[22] = 32;
+ data[23] = 32;
+ //memset(&data[24], 0, 100-24);
+ zeroPage(pP1, PTF_INTKEY | PTF_LEAF | PTF_LEAFDATA);
+ pBt.pageSizeFixed = true;
#if !SQLITE_OMIT_AUTOVACUUM
- Debug.Assert( pBt.autoVacuum == true || pBt.autoVacuum == false );
- Debug.Assert( pBt.incrVacuum == true || pBt.incrVacuum == false );
- sqlite3Put4byte( data, 36 + 4 * 4, pBt.autoVacuum ? 1 : 0 );
- sqlite3Put4byte( data, 36 + 7 * 4, pBt.incrVacuum ? 1 : 0 );
+ Debug.Assert(pBt.autoVacuum == true || pBt.autoVacuum == false);
+ Debug.Assert(pBt.incrVacuum == true || pBt.incrVacuum == false);
+ sqlite3Put4byte(data, 36 + 4 * 4, pBt.autoVacuum ? 1 : 0);
+ sqlite3Put4byte(data, 36 + 7 * 4, pBt.incrVacuum ? 1 : 0);
#endif
- pBt.nPage = 1;
- data[31] = 1;
- return SQLITE_OK;
-}
+ pBt.nPage = 1;
+ data[31] = 1;
+ return SQLITE_OK;
+ }
-/*
-** Attempt to start a new transaction. A write-transaction
-** is started if the second argument is nonzero, otherwise a read-
-** transaction. If the second argument is 2 or more and exclusive
-** transaction is started, meaning that no other process is allowed
-** to access the database. A preexisting transaction may not be
-** upgraded to exclusive by calling this routine a second time - the
-** exclusivity flag only works for a new transaction.
-**
-** A write-transaction must be started before attempting any
-** changes to the database. None of the following routines
-** will work unless a transaction is started first:
-**
-** sqlite3BtreeCreateTable()
-** sqlite3BtreeCreateIndex()
-** sqlite3BtreeClearTable()
-** sqlite3BtreeDropTable()
-** sqlite3BtreeInsert()
-** sqlite3BtreeDelete()
-** sqlite3BtreeUpdateMeta()
-**
-** If an initial attempt to acquire the lock fails because of lock contention
-** and the database was previously unlocked, then invoke the busy handler
-** if there is one. But if there was previously a read-lock, do not
-** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
-** returned when there is already a read-lock in order to avoid a deadlock.
-**
-** Suppose there are two processes A and B. A has a read lock and B has
-** a reserved lock. B tries to promote to exclusive but is blocked because
-** of A's read lock. A tries to promote to reserved but is blocked by B.
-** One or the other of the two processes must give way or there can be
-** no progress. By returning SQLITE_BUSY and not invoking the busy callback
-** when A already has a read lock, we encourage A to give up and let B
-** proceed.
-*/
-static int sqlite3BtreeBeginTrans( Btree p, int wrflag )
-{
- BtShared pBt = p.pBt;
- int rc = SQLITE_OK;
-
- sqlite3BtreeEnter( p );
- btreeIntegrity( p );
-
- /* If the btree is already in a write-transaction, or it
- ** is already in a read-transaction and a read-transaction
- ** is requested, this is a no-op.
- */
- if ( p.inTrans == TRANS_WRITE || ( p.inTrans == TRANS_READ && 0 == wrflag ) )
- {
- goto trans_begun;
- }
-
- /* Write transactions are not possible on a read-only database */
- if ( pBt.readOnly && wrflag != 0 )
- {
- rc = SQLITE_READONLY;
- goto trans_begun;
- }
+ /*
+ ** Attempt to start a new transaction. A write-transaction
+ ** is started if the second argument is nonzero, otherwise a read-
+ ** transaction. If the second argument is 2 or more and exclusive
+ ** transaction is started, meaning that no other process is allowed
+ ** to access the database. A preexisting transaction may not be
+ ** upgraded to exclusive by calling this routine a second time - the
+ ** exclusivity flag only works for a new transaction.
+ **
+ ** A write-transaction must be started before attempting any
+ ** changes to the database. None of the following routines
+ ** will work unless a transaction is started first:
+ **
+ ** sqlite3BtreeCreateTable()
+ ** sqlite3BtreeCreateIndex()
+ ** sqlite3BtreeClearTable()
+ ** sqlite3BtreeDropTable()
+ ** sqlite3BtreeInsert()
+ ** sqlite3BtreeDelete()
+ ** sqlite3BtreeUpdateMeta()
+ **
+ ** If an initial attempt to acquire the lock fails because of lock contention
+ ** and the database was previously unlocked, then invoke the busy handler
+ ** if there is one. But if there was previously a read-lock, do not
+ ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
+ ** returned when there is already a read-lock in order to avoid a deadlock.
+ **
+ ** Suppose there are two processes A and B. A has a read lock and B has
+ ** a reserved lock. B tries to promote to exclusive but is blocked because
+ ** of A's read lock. A tries to promote to reserved but is blocked by B.
+ ** One or the other of the two processes must give way or there can be
+ ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
+ ** when A already has a read lock, we encourage A to give up and let B
+ ** proceed.
+ */
+ static int sqlite3BtreeBeginTrans(Btree p, int wrflag) {
+ BtShared pBt = p.pBt;
+ int rc = SQLITE_OK;
+
+ sqlite3BtreeEnter(p);
+ btreeIntegrity(p);
+
+ /* If the btree is already in a write-transaction, or it
+ ** is already in a read-transaction and a read-transaction
+ ** is requested, this is a no-op.
+ */
+ if (p.inTrans == TRANS_WRITE || (p.inTrans == TRANS_READ && 0 == wrflag)) {
+ goto trans_begun;
+ }
+
+ /* Write transactions are not possible on a read-only database */
+ if (pBt.readOnly && wrflag != 0) {
+ rc = SQLITE_READONLY;
+ goto trans_begun;
+ }
#if !SQLITE_OMIT_SHARED_CACHE
/* If another database handle has already opened a write transaction
@@ -2966,54 +2750,45 @@ static int sqlite3BtreeBeginTrans( Btree p, int wrflag )
}
#endif
- /* Any read-only or read-write transaction implies a read-lock on
-** page 1. So if some other shared-cache client already has a write-lock
-** on page 1, the transaction cannot be opened. */
- rc = querySharedCacheTableLock( p, MASTER_ROOT, READ_LOCK );
- if ( SQLITE_OK != rc )
- goto trans_begun;
-
- pBt.initiallyEmpty = pBt.nPage == 0;
- do
- {
- /* Call lockBtree() until either pBt.pPage1 is populated or
- ** lockBtree() returns something other than SQLITE_OK. lockBtree()
- ** may return SQLITE_OK but leave pBt.pPage1 set to 0 if after
- ** reading page 1 it discovers that the page-size of the database
- ** file is not pBt.pageSize. In this case lockBtree() will update
- ** pBt.pageSize to the page-size of the file on disk.
- */
- while ( pBt.pPage1 == null && SQLITE_OK == ( rc = lockBtree( pBt ) ) )
- ;
-
- if ( rc == SQLITE_OK && wrflag != 0 )
- {
- if ( pBt.readOnly )
- {
- rc = SQLITE_READONLY;
- }
- else
- {
- rc = sqlite3PagerBegin( pBt.pPager, wrflag > 1, sqlite3TempInMemory( p.db ) ? 1 : 0 );
- if ( rc == SQLITE_OK )
- {
- rc = newDatabase( pBt );
- }
- }
- }
-
- if ( rc != SQLITE_OK )
- {
- unlockBtreeIfUnused( pBt );
- }
- } while ( ( rc & 0xFF ) == SQLITE_BUSY && pBt.inTransaction == TRANS_NONE &&
- btreeInvokeBusyHandler( pBt ) != 0 );
-
- if ( rc == SQLITE_OK )
- {
- if ( p.inTrans == TRANS_NONE )
- {
- pBt.nTransaction++;
+ /* Any read-only or read-write transaction implies a read-lock on
+ ** page 1. So if some other shared-cache client already has a write-lock
+ ** on page 1, the transaction cannot be opened. */
+ rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
+ if (SQLITE_OK != rc)
+ goto trans_begun;
+
+ pBt.initiallyEmpty = pBt.nPage == 0;
+ do {
+ /* Call lockBtree() until either pBt.pPage1 is populated or
+ ** lockBtree() returns something other than SQLITE_OK. lockBtree()
+ ** may return SQLITE_OK but leave pBt.pPage1 set to 0 if after
+ ** reading page 1 it discovers that the page-size of the database
+ ** file is not pBt.pageSize. In this case lockBtree() will update
+ ** pBt.pageSize to the page-size of the file on disk.
+ */
+ while (pBt.pPage1 == null && SQLITE_OK == (rc = lockBtree(pBt)))
+ ;
+
+ if (rc == SQLITE_OK && wrflag != 0) {
+ if (pBt.readOnly) {
+ rc = SQLITE_READONLY;
+ } else {
+ rc = sqlite3PagerBegin(pBt.pPager, wrflag > 1, sqlite3TempInMemory(p.db) ? 1 : 0);
+ if (rc == SQLITE_OK) {
+ rc = newDatabase(pBt);
+ }
+ }
+ }
+
+ if (rc != SQLITE_OK) {
+ unlockBtreeIfUnused(pBt);
+ }
+ } while ((rc & 0xFF) == SQLITE_BUSY && pBt.inTransaction == TRANS_NONE &&
+ btreeInvokeBusyHandler(pBt) != 0);
+
+ if (rc == SQLITE_OK) {
+ if (p.inTrans == TRANS_NONE) {
+ pBt.nTransaction++;
#if !SQLITE_OMIT_SHARED_CACHE
if( p.sharable ){
Debug.Assert( p.lock.pBtree==p && p.lock.iTable==1 );
@@ -3022,778 +2797,688 @@ static int sqlite3BtreeBeginTrans( Btree p, int wrflag )
pBt.pLock = &p.lock;
}
#endif
- }
- p.inTrans = ( wrflag != 0 ? TRANS_WRITE : TRANS_READ );
- if ( p.inTrans > pBt.inTransaction )
- {
- pBt.inTransaction = p.inTrans;
- }
- if ( wrflag != 0 )
- {
- MemPage pPage1 = pBt.pPage1;
+ }
+ p.inTrans = (wrflag != 0 ? TRANS_WRITE : TRANS_READ);
+ if (p.inTrans > pBt.inTransaction) {
+ pBt.inTransaction = p.inTrans;
+ }
+ if (wrflag != 0) {
+ MemPage pPage1 = pBt.pPage1;
#if !SQLITE_OMIT_SHARED_CACHE
Debug.Assert( !pBt.pWriter );
pBt.pWriter = p;
pBt.isExclusive = (u8)(wrflag>1);
#endif
- /* If the db-size header field is incorrect (as it may be if an old
-** client has been writing the database file), update it now. Doing
-** this sooner rather than later means the database size can safely
-** re-read the database size from page 1 if a savepoint or transaction
-** rollback occurs within the transaction.
-*/
- if ( pBt.nPage != sqlite3Get4byte( pPage1.aData, 28 ) )
- {
- rc = sqlite3PagerWrite( pPage1.pDbPage );
- if ( rc == SQLITE_OK )
- {
- sqlite3Put4byte( pPage1.aData, (u32)28, pBt.nPage );
- }
- }
- }
- }
-
-
-trans_begun:
- if ( rc == SQLITE_OK && wrflag != 0 )
- {
- /* This call makes sure that the pager has the correct number of
- ** open savepoints. If the second parameter is greater than 0 and
- ** the sub-journal is not already open, then it will be opened here.
- */
- rc = sqlite3PagerOpenSavepoint( pBt.pPager, p.db.nSavepoint );
- }
-
- btreeIntegrity( p );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /* If the db-size header field is incorrect (as it may be if an old
+ ** client has been writing the database file), update it now. Doing
+ ** this sooner rather than later means the database size can safely
+ ** re-read the database size from page 1 if a savepoint or transaction
+ ** rollback occurs within the transaction.
+ */
+ if (pBt.nPage != sqlite3Get4byte(pPage1.aData, 28)) {
+ rc = sqlite3PagerWrite(pPage1.pDbPage);
+ if (rc == SQLITE_OK) {
+ sqlite3Put4byte(pPage1.aData, (u32)28, pBt.nPage);
+ }
+ }
+ }
+ }
-#if !SQLITE_OMIT_AUTOVACUUM
-/*
-** Set the pointer-map entries for all children of page pPage. Also, if
-** pPage contains cells that point to overflow pages, set the pointer
-** map entries for the overflow pages as well.
-*/
-static int setChildPtrmaps( MemPage pPage )
-{
- int i; /* Counter variable */
- int nCell; /* Number of cells in page pPage */
- int rc; /* Return code */
- BtShared pBt = pPage.pBt;
- u8 isInitOrig = pPage.isInit;
- Pgno pgno = pPage.pgno;
-
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- rc = btreeInitPage( pPage );
- if ( rc != SQLITE_OK )
- {
- goto set_child_ptrmaps_out;
- }
- nCell = pPage.nCell;
-
- for ( i = 0; i < nCell; i++ )
- {
- int pCell = findCell( pPage, i );
-
- ptrmapPutOvflPtr( pPage, pCell, ref rc );
-
- if ( 0 == pPage.leaf )
- {
- Pgno childPgno = sqlite3Get4byte( pPage.aData, pCell );
- ptrmapPut( pBt, childPgno, PTRMAP_BTREE, pgno, ref rc );
- }
- }
+ trans_begun:
+ if (rc == SQLITE_OK && wrflag != 0) {
+ /* This call makes sure that the pager has the correct number of
+ ** open savepoints. If the second parameter is greater than 0 and
+ ** the sub-journal is not already open, then it will be opened here.
+ */
+ rc = sqlite3PagerOpenSavepoint(pBt.pPager, p.db.nSavepoint);
+ }
- if ( 0 == pPage.leaf )
- {
- Pgno childPgno = sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 );
- ptrmapPut( pBt, childPgno, PTRMAP_BTREE, pgno, ref rc );
- }
+ btreeIntegrity(p);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-set_child_ptrmaps_out:
- pPage.isInit = isInitOrig;
- return rc;
-}
+#if !SQLITE_OMIT_AUTOVACUUM
-/*
-** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
-** that it points to iTo. Parameter eType describes the type of pointer to
-** be modified, as follows:
-**
-** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
-** page of pPage.
-**
-** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
-** page pointed to by one of the cells on pPage.
-**
-** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
-** overflow page in the list.
-*/
-static int modifyPagePointer( MemPage pPage, Pgno iFrom, Pgno iTo, u8 eType )
-{
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- if ( eType == PTRMAP_OVERFLOW2 )
- {
- /* The pointer is always the first 4 bytes of the page in this case. */
- if ( sqlite3Get4byte( pPage.aData ) != iFrom )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- sqlite3Put4byte( pPage.aData, iTo );
- }
- else
- {
- u8 isInitOrig = pPage.isInit;
- int i;
- int nCell;
-
- btreeInitPage( pPage );
- nCell = pPage.nCell;
-
- for ( i = 0; i < nCell; i++ )
- {
- int pCell = findCell( pPage, i );
- if ( eType == PTRMAP_OVERFLOW1 )
- {
- CellInfo info = new CellInfo();
- btreeParseCellPtr( pPage, pCell, ref info );
- if ( info.iOverflow != 0 )
- {
- if ( iFrom == sqlite3Get4byte( pPage.aData, pCell, info.iOverflow ) )
- {
- sqlite3Put4byte( pPage.aData, pCell + info.iOverflow, (int)iTo );
- break;
- }
- }
- }
- else
- {
- if ( sqlite3Get4byte( pPage.aData, pCell ) == iFrom )
- {
- sqlite3Put4byte( pPage.aData, pCell, (int)iTo );
- break;
- }
- }
- }
+ /*
+ ** Set the pointer-map entries for all children of page pPage. Also, if
+ ** pPage contains cells that point to overflow pages, set the pointer
+ ** map entries for the overflow pages as well.
+ */
+ static int setChildPtrmaps(MemPage pPage) {
+ int i; /* Counter variable */
+ int nCell; /* Number of cells in page pPage */
+ int rc; /* Return code */
+ BtShared pBt = pPage.pBt;
+ u8 isInitOrig = pPage.isInit;
+ Pgno pgno = pPage.pgno;
+
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ rc = btreeInitPage(pPage);
+ if (rc != SQLITE_OK) {
+ goto set_child_ptrmaps_out;
+ }
+ nCell = pPage.nCell;
- if ( i == nCell )
- {
- if ( eType != PTRMAP_BTREE ||
- sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 ) != iFrom )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- sqlite3Put4byte( pPage.aData, pPage.hdrOffset + 8, iTo );
- }
+ for (i = 0; i < nCell; i++) {
+ int pCell = findCell(pPage, i);
- pPage.isInit = isInitOrig;
- }
- return SQLITE_OK;
-}
+ ptrmapPutOvflPtr(pPage, pCell, ref rc);
+ if (0 == pPage.leaf) {
+ Pgno childPgno = sqlite3Get4byte(pPage.aData, pCell);
+ ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, ref rc);
+ }
+ }
-/*
-** Move the open database page pDbPage to location iFreePage in the
-** database. The pDbPage reference remains valid.
-**
-** The isCommit flag indicates that there is no need to remember that
-** the journal needs to be sync()ed before database page pDbPage.pgno
-** can be written to. The caller has already promised not to write to that
-** page.
-*/
-static int relocatePage(
-BtShared pBt, /* Btree */
-MemPage pDbPage, /* Open page to move */
-u8 eType, /* Pointer map 'type' entry for pDbPage */
-Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
-Pgno iFreePage, /* The location to move pDbPage to */
-int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
-)
-{
- MemPage pPtrPage = new MemPage(); /* The page that contains a pointer to pDbPage */
- Pgno iDbPage = pDbPage.pgno;
- Pager pPager = pBt.pPager;
- int rc;
-
- Debug.Assert( eType == PTRMAP_OVERFLOW2 || eType == PTRMAP_OVERFLOW1 ||
- eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE );
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( pDbPage.pBt == pBt );
-
- /* Move page iDbPage from its current location to page number iFreePage */
- TRACE( "AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
- iDbPage, iFreePage, iPtrPage, eType );
- rc = sqlite3PagerMovepage( pPager, pDbPage.pDbPage, iFreePage, isCommit );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- pDbPage.pgno = iFreePage;
-
- /* If pDbPage was a btree-page, then it may have child pages and/or cells
- ** that point to overflow pages. The pointer map entries for all these
- ** pages need to be changed.
- **
- ** If pDbPage is an overflow page, then the first 4 bytes may store a
- ** pointer to a subsequent overflow page. If this is the case, then
- ** the pointer map needs to be updated for the subsequent overflow page.
- */
- if ( eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE )
- {
- rc = setChildPtrmaps( pDbPage );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- }
- else
- {
- Pgno nextOvfl = sqlite3Get4byte( pDbPage.aData );
- if ( nextOvfl != 0 )
- {
- ptrmapPut( pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, ref rc );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- }
- }
-
- /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
- ** that it points at iFreePage. Also fix the pointer map entry for
- ** iPtrPage.
- */
- if ( eType != PTRMAP_ROOTPAGE )
- {
- rc = btreeGetPage( pBt, iPtrPage, ref pPtrPage, 0 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- rc = sqlite3PagerWrite( pPtrPage.pDbPage );
- if ( rc != SQLITE_OK )
- {
- releasePage( pPtrPage );
- return rc;
- }
- rc = modifyPagePointer( pPtrPage, iDbPage, iFreePage, eType );
- releasePage( pPtrPage );
- if ( rc == SQLITE_OK )
- {
- ptrmapPut( pBt, iFreePage, eType, iPtrPage, ref rc );
- }
- }
- return rc;
-}
+ if (0 == pPage.leaf) {
+ Pgno childPgno = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8);
+ ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, ref rc);
+ }
-/* Forward declaration required by incrVacuumStep(). */
-//static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
+ set_child_ptrmaps_out:
+ pPage.isInit = isInitOrig;
+ return rc;
+ }
-/*
-** Perform a single step of an incremental-vacuum. If successful,
-** return SQLITE_OK. If there is no work to do (and therefore no
-** point in calling this function again), return SQLITE_DONE.
-**
-** More specificly, this function attempts to re-organize the
-** database so that the last page of the file currently in use
-** is no longer in use.
-**
-** If the nFin parameter is non-zero, this function assumes
-** that the caller will keep calling incrVacuumStep() until
-** it returns SQLITE_DONE or an error, and that nFin is the
-** number of pages the database file will contain after this
-** process is complete. If nFin is zero, it is assumed that
-** incrVacuumStep() will be called a finite amount of times
-** which may or may not empty the freelist. A full autovacuum
-** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==null.
-*/
-static int incrVacuumStep( BtShared pBt, Pgno nFin, Pgno iLastPg )
-{
- Pgno nFreeList; /* Number of pages still on the free-list */
- int rc;
+ /*
+ ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
+ ** that it points to iTo. Parameter eType describes the type of pointer to
+ ** be modified, as follows:
+ **
+ ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
+ ** page of pPage.
+ **
+ ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
+ ** page pointed to by one of the cells on pPage.
+ **
+ ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
+ ** overflow page in the list.
+ */
+ static int modifyPagePointer(MemPage pPage, Pgno iFrom, Pgno iTo, u8 eType) {
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ if (eType == PTRMAP_OVERFLOW2) {
+ /* The pointer is always the first 4 bytes of the page in this case. */
+ if (sqlite3Get4byte(pPage.aData) != iFrom) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ sqlite3Put4byte(pPage.aData, iTo);
+ } else {
+ u8 isInitOrig = pPage.isInit;
+ int i;
+ int nCell;
+
+ btreeInitPage(pPage);
+ nCell = pPage.nCell;
+
+ for (i = 0; i < nCell; i++) {
+ int pCell = findCell(pPage, i);
+ if (eType == PTRMAP_OVERFLOW1) {
+ CellInfo info = new CellInfo();
+ btreeParseCellPtr(pPage, pCell, ref info);
+ if (info.iOverflow != 0) {
+ if (iFrom == sqlite3Get4byte(pPage.aData, pCell, info.iOverflow)) {
+ sqlite3Put4byte(pPage.aData, pCell + info.iOverflow, (int)iTo);
+ break;
+ }
+ }
+ } else {
+ if (sqlite3Get4byte(pPage.aData, pCell) == iFrom) {
+ sqlite3Put4byte(pPage.aData, pCell, (int)iTo);
+ break;
+ }
+ }
+ }
+
+ if (i == nCell) {
+ if (eType != PTRMAP_BTREE ||
+ sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8) != iFrom) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ sqlite3Put4byte(pPage.aData, pPage.hdrOffset + 8, iTo);
+ }
+
+ pPage.isInit = isInitOrig;
+ }
+ return SQLITE_OK;
+ }
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( iLastPg > nFin );
- if ( !PTRMAP_ISPAGE( pBt, iLastPg ) && iLastPg != PENDING_BYTE_PAGE( pBt ) )
- {
- u8 eType = 0;
- Pgno iPtrPage = 0;
+ /*
+ ** Move the open database page pDbPage to location iFreePage in the
+ ** database. The pDbPage reference remains valid.
+ **
+ ** The isCommit flag indicates that there is no need to remember that
+ ** the journal needs to be sync()ed before database page pDbPage.pgno
+ ** can be written to. The caller has already promised not to write to that
+ ** page.
+ */
+ static int relocatePage(
+ BtShared pBt, /* Btree */
+ MemPage pDbPage, /* Open page to move */
+ u8 eType, /* Pointer map 'type' entry for pDbPage */
+ Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
+ Pgno iFreePage, /* The location to move pDbPage to */
+ int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
+ ) {
+ MemPage pPtrPage = new MemPage(); /* The page that contains a pointer to pDbPage */
+ Pgno iDbPage = pDbPage.pgno;
+ Pager pPager = pBt.pPager;
+ int rc;
+
+ Debug.Assert(eType == PTRMAP_OVERFLOW2 || eType == PTRMAP_OVERFLOW1 ||
+ eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE);
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(pDbPage.pBt == pBt);
+
+ /* Move page iDbPage from its current location to page number iFreePage */
+ TRACE("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
+ iDbPage, iFreePage, iPtrPage, eType);
+ rc = sqlite3PagerMovepage(pPager, pDbPage.pDbPage, iFreePage, isCommit);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ pDbPage.pgno = iFreePage;
+
+ /* If pDbPage was a btree-page, then it may have child pages and/or cells
+ ** that point to overflow pages. The pointer map entries for all these
+ ** pages need to be changed.
+ **
+ ** If pDbPage is an overflow page, then the first 4 bytes may store a
+ ** pointer to a subsequent overflow page. If this is the case, then
+ ** the pointer map needs to be updated for the subsequent overflow page.
+ */
+ if (eType == PTRMAP_BTREE || eType == PTRMAP_ROOTPAGE) {
+ rc = setChildPtrmaps(pDbPage);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ } else {
+ Pgno nextOvfl = sqlite3Get4byte(pDbPage.aData);
+ if (nextOvfl != 0) {
+ ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, ref rc);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ }
+ }
- nFreeList = sqlite3Get4byte( pBt.pPage1.aData, 36 );
- if ( nFreeList == 0 )
- {
- return SQLITE_DONE;
- }
+ /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
+ ** that it points at iFreePage. Also fix the pointer map entry for
+ ** iPtrPage.
+ */
+ if (eType != PTRMAP_ROOTPAGE) {
+ rc = btreeGetPage(pBt, iPtrPage, ref pPtrPage, 0);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ rc = sqlite3PagerWrite(pPtrPage.pDbPage);
+ if (rc != SQLITE_OK) {
+ releasePage(pPtrPage);
+ return rc;
+ }
+ rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
+ releasePage(pPtrPage);
+ if (rc == SQLITE_OK) {
+ ptrmapPut(pBt, iFreePage, eType, iPtrPage, ref rc);
+ }
+ }
+ return rc;
+ }
- rc = ptrmapGet( pBt, iLastPg, ref eType, ref iPtrPage );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- if ( eType == PTRMAP_ROOTPAGE )
- {
- return SQLITE_CORRUPT_BKPT();
- }
+ /* Forward declaration required by incrVacuumStep(). */
+ //static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
- if ( eType == PTRMAP_FREEPAGE )
- {
- if ( nFin == 0 )
- {
- /* Remove the page from the files free-list. This is not required
- ** if nFin is non-zero. In that case, the free-list will be
- ** truncated to zero after this function returns, so it doesn't
- ** matter if it still contains some garbage entries.
- */
- Pgno iFreePg = 0;
- MemPage pFreePg = new MemPage();
- rc = allocateBtreePage( pBt, ref pFreePg, ref iFreePg, iLastPg, 1 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- Debug.Assert( iFreePg == iLastPg );
- releasePage( pFreePg );
- }
- }
- else
- {
- Pgno iFreePg = 0; /* Index of free page to move pLastPg to */
- MemPage pLastPg = new MemPage();
-
- rc = btreeGetPage( pBt, iLastPg, ref pLastPg, 0 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
-
- /* If nFin is zero, this loop runs exactly once and page pLastPg
- ** is swapped with the first free page pulled off the free list.
- **
- ** On the other hand, if nFin is greater than zero, then keep
- ** looping until a free-page located within the first nFin pages
- ** of the file is found.
- */
- do
- {
- MemPage pFreePg = new MemPage();
- rc = allocateBtreePage( pBt, ref pFreePg, ref iFreePg, 0, 0 );
- if ( rc != SQLITE_OK )
- {
- releasePage( pLastPg );
- return rc;
- }
- releasePage( pFreePg );
- } while ( nFin != 0 && iFreePg > nFin );
- Debug.Assert( iFreePg < iLastPg );
-
- rc = sqlite3PagerWrite( pLastPg.pDbPage );
- if ( rc == SQLITE_OK )
- {
- rc = relocatePage( pBt, pLastPg, eType, iPtrPage, iFreePg, ( nFin != 0 ) ? 1 : 0 );
- }
- releasePage( pLastPg );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- }
- }
+ /*
+ ** Perform a single step of an incremental-vacuum. If successful,
+ ** return SQLITE_OK. If there is no work to do (and therefore no
+ ** point in calling this function again), return SQLITE_DONE.
+ **
+ ** More specificly, this function attempts to re-organize the
+ ** database so that the last page of the file currently in use
+ ** is no longer in use.
+ **
+ ** If the nFin parameter is non-zero, this function assumes
+ ** that the caller will keep calling incrVacuumStep() until
+ ** it returns SQLITE_DONE or an error, and that nFin is the
+ ** number of pages the database file will contain after this
+ ** process is complete. If nFin is zero, it is assumed that
+ ** incrVacuumStep() will be called a finite amount of times
+ ** which may or may not empty the freelist. A full autovacuum
+ ** has nFin>0. A "PRAGMA incremental_vacuum" has nFin==null.
+ */
+ static int incrVacuumStep(BtShared pBt, Pgno nFin, Pgno iLastPg) {
+ Pgno nFreeList; /* Number of pages still on the free-list */
+ int rc;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(iLastPg > nFin);
+
+ if (!PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg != PENDING_BYTE_PAGE(pBt)) {
+ u8 eType = 0;
+ Pgno iPtrPage = 0;
+
+ nFreeList = sqlite3Get4byte(pBt.pPage1.aData, 36);
+ if (nFreeList == 0) {
+ return SQLITE_DONE;
+ }
+
+ rc = ptrmapGet(pBt, iLastPg, ref eType, ref iPtrPage);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ if (eType == PTRMAP_ROOTPAGE) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+
+ if (eType == PTRMAP_FREEPAGE) {
+ if (nFin == 0) {
+ /* Remove the page from the files free-list. This is not required
+ ** if nFin is non-zero. In that case, the free-list will be
+ ** truncated to zero after this function returns, so it doesn't
+ ** matter if it still contains some garbage entries.
+ */
+ Pgno iFreePg = 0;
+ MemPage pFreePg = new MemPage();
+ rc = allocateBtreePage(pBt, ref pFreePg, ref iFreePg, iLastPg, 1);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ Debug.Assert(iFreePg == iLastPg);
+ releasePage(pFreePg);
+ }
+ } else {
+ Pgno iFreePg = 0; /* Index of free page to move pLastPg to */
+ MemPage pLastPg = new MemPage();
+
+ rc = btreeGetPage(pBt, iLastPg, ref pLastPg, 0);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+
+ /* If nFin is zero, this loop runs exactly once and page pLastPg
+ ** is swapped with the first free page pulled off the free list.
+ **
+ ** On the other hand, if nFin is greater than zero, then keep
+ ** looping until a free-page located within the first nFin pages
+ ** of the file is found.
+ */
+ do {
+ MemPage pFreePg = new MemPage();
+ rc = allocateBtreePage(pBt, ref pFreePg, ref iFreePg, 0, 0);
+ if (rc != SQLITE_OK) {
+ releasePage(pLastPg);
+ return rc;
+ }
+ releasePage(pFreePg);
+ } while (nFin != 0 && iFreePg > nFin);
+ Debug.Assert(iFreePg < iLastPg);
+
+ rc = sqlite3PagerWrite(pLastPg.pDbPage);
+ if (rc == SQLITE_OK) {
+ rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, (nFin != 0) ? 1 : 0);
+ }
+ releasePage(pLastPg);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ }
+ }
- if ( nFin == 0 )
- {
- iLastPg--;
- while ( iLastPg == PENDING_BYTE_PAGE( pBt ) || PTRMAP_ISPAGE( pBt, iLastPg ) )
- {
- if ( PTRMAP_ISPAGE( pBt, iLastPg ) )
- {
- MemPage pPg = new MemPage();
- rc = btreeGetPage( pBt, iLastPg, ref pPg, 0 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- rc = sqlite3PagerWrite( pPg.pDbPage );
- releasePage( pPg );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- }
- iLastPg--;
- }
- sqlite3PagerTruncateImage( pBt.pPager, iLastPg );
- pBt.nPage = iLastPg;
- }
- return SQLITE_OK;
-}
+ if (nFin == 0) {
+ iLastPg--;
+ while (iLastPg == PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg)) {
+ if (PTRMAP_ISPAGE(pBt, iLastPg)) {
+ MemPage pPg = new MemPage();
+ rc = btreeGetPage(pBt, iLastPg, ref pPg, 0);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ rc = sqlite3PagerWrite(pPg.pDbPage);
+ releasePage(pPg);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ }
+ iLastPg--;
+ }
+ sqlite3PagerTruncateImage(pBt.pPager, iLastPg);
+ pBt.nPage = iLastPg;
+ }
+ return SQLITE_OK;
+ }
-/*
-** A write-transaction must be opened before calling this function.
-** It performs a single unit of work towards an incremental vacuum.
-**
-** If the incremental vacuum is finished after this function has run,
-** SQLITE_DONE is returned. If it is not finished, but no error occurred,
-** SQLITE_OK is returned. Otherwise an SQLite error code.
-*/
-static int sqlite3BtreeIncrVacuum( Btree p )
-{
- int rc;
- BtShared pBt = p.pBt;
-
- sqlite3BtreeEnter( p );
- Debug.Assert( pBt.inTransaction == TRANS_WRITE && p.inTrans == TRANS_WRITE );
- if ( !pBt.autoVacuum )
- {
- rc = SQLITE_DONE;
- }
- else
- {
- invalidateAllOverflowCache( pBt );
- rc = incrVacuumStep( pBt, 0, btreePagecount( pBt ) );
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3PagerWrite( pBt.pPage1.pDbPage );
- sqlite3Put4byte( pBt.pPage1.aData, (u32)28, pBt.nPage );//put4byte(&pBt->pPage1->aData[28], pBt->nPage);
- }
- }
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** A write-transaction must be opened before calling this function.
+ ** It performs a single unit of work towards an incremental vacuum.
+ **
+ ** If the incremental vacuum is finished after this function has run,
+ ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
+ ** SQLITE_OK is returned. Otherwise an SQLite error code.
+ */
+ static int sqlite3BtreeIncrVacuum(Btree p) {
+ int rc;
+ BtShared pBt = p.pBt;
+
+ sqlite3BtreeEnter(p);
+ Debug.Assert(pBt.inTransaction == TRANS_WRITE && p.inTrans == TRANS_WRITE);
+ if (!pBt.autoVacuum) {
+ rc = SQLITE_DONE;
+ } else {
+ invalidateAllOverflowCache(pBt);
+ rc = incrVacuumStep(pBt, 0, btreePagecount(pBt));
+ if (rc == SQLITE_OK) {
+ rc = sqlite3PagerWrite(pBt.pPage1.pDbPage);
+ sqlite3Put4byte(pBt.pPage1.aData, (u32)28, pBt.nPage);//put4byte(&pBt->pPage1->aData[28], pBt->nPage);
+ }
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** This routine is called prior to sqlite3PagerCommit when a transaction
-** is commited for an auto-vacuum database.
-**
-** If SQLITE_OK is returned, then pnTrunc is set to the number of pages
-** the database file should be truncated to during the commit process.
-** i.e. the database has been reorganized so that only the first pnTrunc
-** pages are in use.
-*/
-static int autoVacuumCommit( BtShared pBt )
-{
- int rc = SQLITE_OK;
- Pager pPager = pBt.pPager;
- // VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
+ /*
+ ** This routine is called prior to sqlite3PagerCommit when a transaction
+ ** is commited for an auto-vacuum database.
+ **
+ ** If SQLITE_OK is returned, then pnTrunc is set to the number of pages
+ ** the database file should be truncated to during the commit process.
+ ** i.e. the database has been reorganized so that only the first pnTrunc
+ ** pages are in use.
+ */
+ static int autoVacuumCommit(BtShared pBt) {
+ int rc = SQLITE_OK;
+ Pager pPager = pBt.pPager;
+ // VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
#if !NDEBUG || DEBUG
- int nRef = sqlite3PagerRefcount( pPager );
+ int nRef = sqlite3PagerRefcount(pPager);
#else
int nRef=0;
#endif
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- invalidateAllOverflowCache( pBt );
- Debug.Assert( pBt.autoVacuum );
- if ( !pBt.incrVacuum )
- {
- Pgno nFin; /* Number of pages in database after autovacuuming */
- Pgno nFree; /* Number of pages on the freelist initially */
- Pgno nPtrmap; /* Number of PtrMap pages to be freed */
- Pgno iFree; /* The next page to be freed */
- int nEntry; /* Number of entries on one ptrmap page */
- Pgno nOrig; /* Database size before freeing */
-
- nOrig = btreePagecount( pBt );
- if ( PTRMAP_ISPAGE( pBt, nOrig ) || nOrig == PENDING_BYTE_PAGE( pBt ) )
- {
- /* It is not possible to create a database for which the final page
- ** is either a pointer-map page or the pending-byte page. If one
- ** is encountered, this indicates corruption.
- */
- return SQLITE_CORRUPT_BKPT();
- }
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ invalidateAllOverflowCache(pBt);
+ Debug.Assert(pBt.autoVacuum);
+ if (!pBt.incrVacuum) {
+ Pgno nFin; /* Number of pages in database after autovacuuming */
+ Pgno nFree; /* Number of pages on the freelist initially */
+ Pgno nPtrmap; /* Number of PtrMap pages to be freed */
+ Pgno iFree; /* The next page to be freed */
+ int nEntry; /* Number of entries on one ptrmap page */
+ Pgno nOrig; /* Database size before freeing */
+
+ nOrig = btreePagecount(pBt);
+ if (PTRMAP_ISPAGE(pBt, nOrig) || nOrig == PENDING_BYTE_PAGE(pBt)) {
+ /* It is not possible to create a database for which the final page
+ ** is either a pointer-map page or the pending-byte page. If one
+ ** is encountered, this indicates corruption.
+ */
+ return SQLITE_CORRUPT_BKPT();
+ }
+
+ nFree = sqlite3Get4byte(pBt.pPage1.aData, 36);
+ nEntry = (int)pBt.usableSize / 5;
+ nPtrmap = (Pgno)((nFree - nOrig + PTRMAP_PAGENO(pBt, nOrig) + (Pgno)nEntry) / nEntry);
+ nFin = nOrig - nFree - nPtrmap;
+ if (nOrig > PENDING_BYTE_PAGE(pBt) && nFin < PENDING_BYTE_PAGE(pBt)) {
+ nFin--;
+ }
+ while (PTRMAP_ISPAGE(pBt, nFin) || nFin == PENDING_BYTE_PAGE(pBt)) {
+ nFin--;
+ }
+ if (nFin > nOrig)
+ return SQLITE_CORRUPT_BKPT();
+
+ for (iFree = nOrig; iFree > nFin && rc == SQLITE_OK; iFree--) {
+ rc = incrVacuumStep(pBt, nFin, iFree);
+ }
+ if ((rc == SQLITE_DONE || rc == SQLITE_OK) && nFree > 0) {
+ rc = sqlite3PagerWrite(pBt.pPage1.pDbPage);
+ sqlite3Put4byte(pBt.pPage1.aData, 32, 0);
+ sqlite3Put4byte(pBt.pPage1.aData, 36, 0);
+ sqlite3Put4byte(pBt.pPage1.aData, (u32)28, nFin);
+ sqlite3PagerTruncateImage(pBt.pPager, nFin);
+ pBt.nPage = nFin;
+ }
+ if (rc != SQLITE_OK) {
+ sqlite3PagerRollback(pPager);
+ }
+ }
- nFree = sqlite3Get4byte( pBt.pPage1.aData, 36 );
- nEntry = (int)pBt.usableSize / 5;
- nPtrmap = (Pgno)( ( nFree - nOrig + PTRMAP_PAGENO( pBt, nOrig ) + (Pgno)nEntry ) / nEntry );
- nFin = nOrig - nFree - nPtrmap;
- if ( nOrig > PENDING_BYTE_PAGE( pBt ) && nFin < PENDING_BYTE_PAGE( pBt ) )
- {
- nFin--;
- }
- while ( PTRMAP_ISPAGE( pBt, nFin ) || nFin == PENDING_BYTE_PAGE( pBt ) )
- {
- nFin--;
- }
- if ( nFin > nOrig )
- return SQLITE_CORRUPT_BKPT();
-
- for ( iFree = nOrig; iFree > nFin && rc == SQLITE_OK; iFree-- )
- {
- rc = incrVacuumStep( pBt, nFin, iFree );
- }
- if ( ( rc == SQLITE_DONE || rc == SQLITE_OK ) && nFree > 0 )
- {
- rc = sqlite3PagerWrite( pBt.pPage1.pDbPage );
- sqlite3Put4byte( pBt.pPage1.aData, 32, 0 );
- sqlite3Put4byte( pBt.pPage1.aData, 36, 0 );
- sqlite3Put4byte( pBt.pPage1.aData, (u32)28, nFin );
- sqlite3PagerTruncateImage( pBt.pPager, nFin );
- pBt.nPage = nFin;
- }
- if ( rc != SQLITE_OK )
- {
- sqlite3PagerRollback( pPager );
- }
- }
-
- Debug.Assert( nRef == sqlite3PagerRefcount( pPager ) );
- return rc;
-}
+ Debug.Assert(nRef == sqlite3PagerRefcount(pPager));
+ return rc;
+ }
#else //* ifndef SQLITE_OMIT_AUTOVACUUM */
//# define setChildPtrmaps(x) SQLITE_OK
#endif
-/*
-** This routine does the first phase of a two-phase commit. This routine
-** causes a rollback journal to be created (if it does not already exist)
-** and populated with enough information so that if a power loss occurs
-** the database can be restored to its original state by playing back
-** the journal. Then the contents of the journal are flushed out to
-** the disk. After the journal is safely on oxide, the changes to the
-** database are written into the database file and flushed to oxide.
-** At the end of this call, the rollback journal still exists on the
-** disk and we are still holding all locks, so the transaction has not
-** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
-** commit process.
-**
-** This call is a no-op if no write-transaction is currently active on pBt.
-**
-** Otherwise, sync the database file for the btree pBt. zMaster points to
-** the name of a master journal file that should be written into the
-** individual journal file, or is NULL, indicating no master journal file
-** (single database transaction).
-**
-** When this is called, the master journal should already have been
-** created, populated with this journal pointer and synced to disk.
-**
-** Once this is routine has returned, the only thing required to commit
-** the write-transaction for this database file is to delete the journal.
-*/
-static int sqlite3BtreeCommitPhaseOne( Btree p, string zMaster )
-{
- int rc = SQLITE_OK;
- if ( p.inTrans == TRANS_WRITE )
- {
- BtShared pBt = p.pBt;
- sqlite3BtreeEnter( p );
+ /*
+ ** This routine does the first phase of a two-phase commit. This routine
+ ** causes a rollback journal to be created (if it does not already exist)
+ ** and populated with enough information so that if a power loss occurs
+ ** the database can be restored to its original state by playing back
+ ** the journal. Then the contents of the journal are flushed out to
+ ** the disk. After the journal is safely on oxide, the changes to the
+ ** database are written into the database file and flushed to oxide.
+ ** At the end of this call, the rollback journal still exists on the
+ ** disk and we are still holding all locks, so the transaction has not
+ ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
+ ** commit process.
+ **
+ ** This call is a no-op if no write-transaction is currently active on pBt.
+ **
+ ** Otherwise, sync the database file for the btree pBt. zMaster points to
+ ** the name of a master journal file that should be written into the
+ ** individual journal file, or is NULL, indicating no master journal file
+ ** (single database transaction).
+ **
+ ** When this is called, the master journal should already have been
+ ** created, populated with this journal pointer and synced to disk.
+ **
+ ** Once this is routine has returned, the only thing required to commit
+ ** the write-transaction for this database file is to delete the journal.
+ */
+ static int sqlite3BtreeCommitPhaseOne(Btree p, string zMaster) {
+ int rc = SQLITE_OK;
+ if (p.inTrans == TRANS_WRITE) {
+ BtShared pBt = p.pBt;
+ sqlite3BtreeEnter(p);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pBt.autoVacuum )
- {
- rc = autoVacuumCommit( pBt );
- if ( rc != SQLITE_OK )
- {
- sqlite3BtreeLeave( p );
- return rc;
- }
- }
+ if (pBt.autoVacuum) {
+ rc = autoVacuumCommit(pBt);
+ if (rc != SQLITE_OK) {
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
+ }
#endif
- rc = sqlite3PagerCommitPhaseOne( pBt.pPager, zMaster, false );
- sqlite3BtreeLeave( p );
- }
- return rc;
-}
-
-/*
-** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
-** at the conclusion of a transaction.
-*/
-static void btreeEndTransaction( Btree p )
-{
- BtShared pBt = p.pBt;
- Debug.Assert( sqlite3BtreeHoldsMutex( p ) );
-
- btreeClearHasContent( pBt );
- if ( p.inTrans > TRANS_NONE && p.db.activeVdbeCnt > 1 )
- {
- /* If there are other active statements that belong to this database
- ** handle, downgrade to a read-only transaction. The other statements
- ** may still be reading from the database. */
-
- downgradeAllSharedCacheTableLocks( p );
- p.inTrans = TRANS_READ;
- }
- else
- {
- /* If the handle had any kind of transaction open, decrement the
- ** transaction count of the shared btree. If the transaction count
- ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
- ** call below will unlock the pager. */
- if ( p.inTrans != TRANS_NONE )
- {
- clearAllSharedCacheTableLocks( p );
- pBt.nTransaction--;
- if ( 0 == pBt.nTransaction )
- {
- pBt.inTransaction = TRANS_NONE;
- }
- }
+ rc = sqlite3PagerCommitPhaseOne(pBt.pPager, zMaster, false);
+ sqlite3BtreeLeave(p);
+ }
+ return rc;
+ }
- /* Set the current transaction state to TRANS_NONE and unlock the
- ** pager if this call closed the only read or write transaction. */
- p.inTrans = TRANS_NONE;
- unlockBtreeIfUnused( pBt );
- }
+ /*
+ ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
+ ** at the conclusion of a transaction.
+ */
+ static void btreeEndTransaction(Btree p) {
+ BtShared pBt = p.pBt;
+ Debug.Assert(sqlite3BtreeHoldsMutex(p));
+
+ btreeClearHasContent(pBt);
+ if (p.inTrans > TRANS_NONE && p.db.activeVdbeCnt > 1) {
+ /* If there are other active statements that belong to this database
+ ** handle, downgrade to a read-only transaction. The other statements
+ ** may still be reading from the database. */
+
+ downgradeAllSharedCacheTableLocks(p);
+ p.inTrans = TRANS_READ;
+ } else {
+ /* If the handle had any kind of transaction open, decrement the
+ ** transaction count of the shared btree. If the transaction count
+ ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
+ ** call below will unlock the pager. */
+ if (p.inTrans != TRANS_NONE) {
+ clearAllSharedCacheTableLocks(p);
+ pBt.nTransaction--;
+ if (0 == pBt.nTransaction) {
+ pBt.inTransaction = TRANS_NONE;
+ }
+ }
+
+ /* Set the current transaction state to TRANS_NONE and unlock the
+ ** pager if this call closed the only read or write transaction. */
+ p.inTrans = TRANS_NONE;
+ unlockBtreeIfUnused(pBt);
+ }
- btreeIntegrity( p );
-}
+ btreeIntegrity(p);
+ }
-/*
-** Commit the transaction currently in progress.
-**
-** This routine implements the second phase of a 2-phase commit. The
-** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
-** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
-** routine did all the work of writing information out to disk and flushing the
-** contents so that they are written onto the disk platter. All this
-** routine has to do is delete or truncate or zero the header in the
-** the rollback journal (which causes the transaction to commit) and
-** drop locks.
-**
-** Normally, if an error occurs while the pager layer is attempting to
-** finalize the underlying journal file, this function returns an error and
-** the upper layer will attempt a rollback. However, if the second argument
-** is non-zero then this b-tree transaction is part of a multi-file
-** transaction. In this case, the transaction has already been committed
-** (by deleting a master journal file) and the caller will ignore this
-** functions return code. So, even if an error occurs in the pager layer,
-** reset the b-tree objects internal state to indicate that the write
-** transaction has been closed. This is quite safe, as the pager will have
-** transitioned to the error state.
-**
-** This will release the write lock on the database file. If there
-** are no active cursors, it also releases the read lock.
-*/
-static int sqlite3BtreeCommitPhaseTwo( Btree p, int bCleanup)
-{
- if ( p.inTrans == TRANS_NONE )
- return SQLITE_OK;
- sqlite3BtreeEnter( p );
- btreeIntegrity( p );
-
- /* If the handle has a write-transaction open, commit the shared-btrees
- ** transaction and set the shared state to TRANS_READ.
- */
- if ( p.inTrans == TRANS_WRITE )
- {
- int rc;
- BtShared pBt = p.pBt;
- Debug.Assert( pBt.inTransaction == TRANS_WRITE );
- Debug.Assert( pBt.nTransaction > 0 );
- rc = sqlite3PagerCommitPhaseTwo( pBt.pPager );
- if ( rc != SQLITE_OK && bCleanup == 0 )
- {
- sqlite3BtreeLeave( p );
- return rc;
- }
- pBt.inTransaction = TRANS_READ;
- }
+ /*
+ ** Commit the transaction currently in progress.
+ **
+ ** This routine implements the second phase of a 2-phase commit. The
+ ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
+ ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
+ ** routine did all the work of writing information out to disk and flushing the
+ ** contents so that they are written onto the disk platter. All this
+ ** routine has to do is delete or truncate or zero the header in the
+ ** the rollback journal (which causes the transaction to commit) and
+ ** drop locks.
+ **
+ ** Normally, if an error occurs while the pager layer is attempting to
+ ** finalize the underlying journal file, this function returns an error and
+ ** the upper layer will attempt a rollback. However, if the second argument
+ ** is non-zero then this b-tree transaction is part of a multi-file
+ ** transaction. In this case, the transaction has already been committed
+ ** (by deleting a master journal file) and the caller will ignore this
+ ** functions return code. So, even if an error occurs in the pager layer,
+ ** reset the b-tree objects internal state to indicate that the write
+ ** transaction has been closed. This is quite safe, as the pager will have
+ ** transitioned to the error state.
+ **
+ ** This will release the write lock on the database file. If there
+ ** are no active cursors, it also releases the read lock.
+ */
+ static int sqlite3BtreeCommitPhaseTwo(Btree p, int bCleanup) {
+ if (p.inTrans == TRANS_NONE)
+ return SQLITE_OK;
+ sqlite3BtreeEnter(p);
+ btreeIntegrity(p);
+
+ /* If the handle has a write-transaction open, commit the shared-btrees
+ ** transaction and set the shared state to TRANS_READ.
+ */
+ if (p.inTrans == TRANS_WRITE) {
+ int rc;
+ BtShared pBt = p.pBt;
+ Debug.Assert(pBt.inTransaction == TRANS_WRITE);
+ Debug.Assert(pBt.nTransaction > 0);
+ rc = sqlite3PagerCommitPhaseTwo(pBt.pPager);
+ if (rc != SQLITE_OK && bCleanup == 0) {
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
+ pBt.inTransaction = TRANS_READ;
+ }
- btreeEndTransaction( p );
- sqlite3BtreeLeave( p );
- return SQLITE_OK;
-}
+ btreeEndTransaction(p);
+ sqlite3BtreeLeave(p);
+ return SQLITE_OK;
+ }
-/*
-** Do both phases of a commit.
-*/
-static int sqlite3BtreeCommit( Btree p )
-{
- int rc;
- sqlite3BtreeEnter( p );
- rc = sqlite3BtreeCommitPhaseOne( p, null );
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3BtreeCommitPhaseTwo( p, 0 );
- }
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** Do both phases of a commit.
+ */
+ static int sqlite3BtreeCommit(Btree p) {
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = sqlite3BtreeCommitPhaseOne(p, null);
+ if (rc == SQLITE_OK) {
+ rc = sqlite3BtreeCommitPhaseTwo(p, 0);
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
#if !NDEBUG || DEBUG
-/*
-** Return the number of write-cursors open on this handle. This is for use
-** in Debug.Assert() expressions, so it is only compiled if NDEBUG is not
-** defined.
-**
-** For the purposes of this routine, a write-cursor is any cursor that
-** is capable of writing to the databse. That means the cursor was
-** originally opened for writing and the cursor has not be disabled
-** by having its state changed to CURSOR_FAULT.
-*/
-static int countWriteCursors( BtShared pBt )
-{
- BtCursor pCur;
- int r = 0;
- for ( pCur = pBt.pCursor; pCur != null; pCur = pCur.pNext )
- {
- if ( pCur.wrFlag != 0 && pCur.eState != CURSOR_FAULT )
- r++;
- }
- return r;
-}
+ /*
+ ** Return the number of write-cursors open on this handle. This is for use
+ ** in Debug.Assert() expressions, so it is only compiled if NDEBUG is not
+ ** defined.
+ **
+ ** For the purposes of this routine, a write-cursor is any cursor that
+ ** is capable of writing to the databse. That means the cursor was
+ ** originally opened for writing and the cursor has not be disabled
+ ** by having its state changed to CURSOR_FAULT.
+ */
+ static int countWriteCursors(BtShared pBt) {
+ BtCursor pCur;
+ int r = 0;
+ for (pCur = pBt.pCursor; pCur != null; pCur = pCur.pNext) {
+ if (pCur.wrFlag != 0 && pCur.eState != CURSOR_FAULT)
+ r++;
+ }
+ return r;
+ }
#else
static int countWriteCursors(BtShared pBt) { return -1; }
#endif
-/*
-** This routine sets the state to CURSOR_FAULT and the error
-** code to errCode for every cursor on BtShared that pBtree
-** references.
-**
-** Every cursor is tripped, including cursors that belong
-** to other database connections that happen to be sharing
-** the cache with pBtree.
-**
-** This routine gets called when a rollback occurs.
-** All cursors using the same cache must be tripped
-** to prevent them from trying to use the btree after
-** the rollback. The rollback may have deleted tables
-** or moved root pages, so it is not sufficient to
-** save the state of the cursor. The cursor must be
-** invalidated.
-*/
-static void sqlite3BtreeTripAllCursors( Btree pBtree, int errCode )
-{
- BtCursor p;
- sqlite3BtreeEnter( pBtree );
- for ( p = pBtree.pBt.pCursor; p != null; p = p.pNext )
- {
- int i;
- sqlite3BtreeClearCursor( p );
- p.eState = CURSOR_FAULT;
- p.skipNext = errCode;
- for ( i = 0; i <= p.iPage; i++ )
- {
- releasePage( p.apPage[i] );
- p.apPage[i] = null;
- }
- }
- sqlite3BtreeLeave( pBtree );
-}
+ /*
+ ** This routine sets the state to CURSOR_FAULT and the error
+ ** code to errCode for every cursor on BtShared that pBtree
+ ** references.
+ **
+ ** Every cursor is tripped, including cursors that belong
+ ** to other database connections that happen to be sharing
+ ** the cache with pBtree.
+ **
+ ** This routine gets called when a rollback occurs.
+ ** All cursors using the same cache must be tripped
+ ** to prevent them from trying to use the btree after
+ ** the rollback. The rollback may have deleted tables
+ ** or moved root pages, so it is not sufficient to
+ ** save the state of the cursor. The cursor must be
+ ** invalidated.
+ */
+ static void sqlite3BtreeTripAllCursors(Btree pBtree, int errCode) {
+ BtCursor p;
+ sqlite3BtreeEnter(pBtree);
+ for (p = pBtree.pBt.pCursor; p != null; p = p.pNext) {
+ int i;
+ sqlite3BtreeClearCursor(p);
+ p.eState = CURSOR_FAULT;
+ p.skipNext = errCode;
+ for (i = 0; i <= p.iPage; i++) {
+ releasePage(p.apPage[i]);
+ p.apPage[i] = null;
+ }
+ }
+ sqlite3BtreeLeave(pBtree);
+ }
-/*
-** Rollback the transaction in progress. All cursors will be
-** invalided by this operation. Any attempt to use a cursor
-** that was open at the beginning of this operation will result
-** in an error.
-**
-** This will release the write lock on the database file. If there
-** are no active cursors, it also releases the read lock.
-*/
-static int sqlite3BtreeRollback( Btree p )
-{
- int rc;
- BtShared pBt = p.pBt;
- MemPage pPage1 = new MemPage();
+ /*
+ ** Rollback the transaction in progress. All cursors will be
+ ** invalided by this operation. Any attempt to use a cursor
+ ** that was open at the beginning of this operation will result
+ ** in an error.
+ **
+ ** This will release the write lock on the database file. If there
+ ** are no active cursors, it also releases the read lock.
+ */
+ static int sqlite3BtreeRollback(Btree p) {
+ int rc;
+ BtShared pBt = p.pBt;
+ MemPage pPage1 = new MemPage();
- sqlite3BtreeEnter( p );
- rc = saveAllCursors( pBt, 0, null );
+ sqlite3BtreeEnter(p);
+ rc = saveAllCursors(pBt, 0, null);
#if !SQLITE_OMIT_SHARED_CACHE
if( rc!=SQLITE_OK ){
/* This is a horrible situation. An IO or malloc() error occurred whilst
@@ -3806,356 +3491,327 @@ static int sqlite3BtreeRollback( Btree p )
sqlite3BtreeTripAllCursors(p, rc);
}
#endif
- btreeIntegrity( p );
-
- if ( p.inTrans == TRANS_WRITE )
- {
- int rc2;
-
- Debug.Assert( TRANS_WRITE == pBt.inTransaction );
- rc2 = sqlite3PagerRollback( pBt.pPager );
- if ( rc2 != SQLITE_OK )
- {
- rc = rc2;
- }
+ btreeIntegrity(p);
+
+ if (p.inTrans == TRANS_WRITE) {
+ int rc2;
+
+ Debug.Assert(TRANS_WRITE == pBt.inTransaction);
+ rc2 = sqlite3PagerRollback(pBt.pPager);
+ if (rc2 != SQLITE_OK) {
+ rc = rc2;
+ }
+
+ /* The rollback may have destroyed the pPage1.aData value. So
+ ** call btreeGetPage() on page 1 again to make
+ ** sure pPage1.aData is set correctly. */
+ if (btreeGetPage(pBt, 1, ref pPage1, 0) == SQLITE_OK) {
+ Pgno nPage = sqlite3Get4byte(pPage1.aData, 28);
+ testcase(nPage == 0);
+ if (nPage == 0)
+ sqlite3PagerPagecount(pBt.pPager, out nPage);
+ testcase(pBt.nPage != nPage);
+ pBt.nPage = nPage;
+ releasePage(pPage1);
+ }
+ Debug.Assert(countWriteCursors(pBt) == 0);
+ pBt.inTransaction = TRANS_READ;
+ }
- /* The rollback may have destroyed the pPage1.aData value. So
- ** call btreeGetPage() on page 1 again to make
- ** sure pPage1.aData is set correctly. */
- if ( btreeGetPage( pBt, 1, ref pPage1, 0 ) == SQLITE_OK )
- {
- Pgno nPage = sqlite3Get4byte( pPage1.aData, 28 );
- testcase( nPage == 0 );
- if ( nPage == 0 )
- sqlite3PagerPagecount( pBt.pPager, out nPage );
- testcase( pBt.nPage != nPage );
- pBt.nPage = nPage;
- releasePage( pPage1 );
- }
- Debug.Assert( countWriteCursors( pBt ) == 0 );
- pBt.inTransaction = TRANS_READ;
- }
+ btreeEndTransaction(p);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
- btreeEndTransaction( p );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** Start a statement subtransaction. The subtransaction can can be rolled
+ ** back independently of the main transaction. You must start a transaction
+ ** before starting a subtransaction. The subtransaction is ended automatically
+ ** if the main transaction commits or rolls back.
+ **
+ ** Statement subtransactions are used around individual SQL statements
+ ** that are contained within a BEGIN...COMMIT block. If a constraint
+ ** error occurs within the statement, the effect of that one statement
+ ** can be rolled back without having to rollback the entire transaction.
+ **
+ ** A statement sub-transaction is implemented as an anonymous savepoint. The
+ ** value passed as the second parameter is the total number of savepoints,
+ ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
+ ** are no active savepoints and no other statement-transactions open,
+ ** iStatement is 1. This anonymous savepoint can be released or rolled back
+ ** using the sqlite3BtreeSavepoint() function.
+ */
+ static int sqlite3BtreeBeginStmt(Btree p, int iStatement) {
+ int rc;
+ BtShared pBt = p.pBt;
+ sqlite3BtreeEnter(p);
+ Debug.Assert(p.inTrans == TRANS_WRITE);
+ Debug.Assert(!pBt.readOnly);
+ Debug.Assert(iStatement > 0);
+ Debug.Assert(iStatement > p.db.nSavepoint);
+ Debug.Assert(pBt.inTransaction == TRANS_WRITE);
+ /* At the pager level, a statement transaction is a savepoint with
+ ** an index greater than all savepoints created explicitly using
+ ** SQL statements. It is illegal to open, release or rollback any
+ ** such savepoints while the statement transaction savepoint is active.
+ */
+ rc = sqlite3PagerOpenSavepoint(pBt.pPager, iStatement);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** Start a statement subtransaction. The subtransaction can can be rolled
-** back independently of the main transaction. You must start a transaction
-** before starting a subtransaction. The subtransaction is ended automatically
-** if the main transaction commits or rolls back.
-**
-** Statement subtransactions are used around individual SQL statements
-** that are contained within a BEGIN...COMMIT block. If a constraint
-** error occurs within the statement, the effect of that one statement
-** can be rolled back without having to rollback the entire transaction.
-**
-** A statement sub-transaction is implemented as an anonymous savepoint. The
-** value passed as the second parameter is the total number of savepoints,
-** including the new anonymous savepoint, open on the B-Tree. i.e. if there
-** are no active savepoints and no other statement-transactions open,
-** iStatement is 1. This anonymous savepoint can be released or rolled back
-** using the sqlite3BtreeSavepoint() function.
-*/
-static int sqlite3BtreeBeginStmt( Btree p, int iStatement )
-{
- int rc;
- BtShared pBt = p.pBt;
- sqlite3BtreeEnter( p );
- Debug.Assert( p.inTrans == TRANS_WRITE );
- Debug.Assert( !pBt.readOnly );
- Debug.Assert( iStatement > 0 );
- Debug.Assert( iStatement > p.db.nSavepoint );
- Debug.Assert( pBt.inTransaction == TRANS_WRITE );
- /* At the pager level, a statement transaction is a savepoint with
- ** an index greater than all savepoints created explicitly using
- ** SQL statements. It is illegal to open, release or rollback any
- ** such savepoints while the statement transaction savepoint is active.
- */
- rc = sqlite3PagerOpenSavepoint( pBt.pPager, iStatement );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
+ ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
+ ** savepoint identified by parameter iSavepoint, depending on the value
+ ** of op.
+ **
+ ** Normally, iSavepoint is greater than or equal to zero. However, if op is
+ ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
+ ** contents of the entire transaction are rolled back. This is different
+ ** from a normal transaction rollback, as no locks are released and the
+ ** transaction remains open.
+ */
+ static int sqlite3BtreeSavepoint(Btree p, int op, int iSavepoint) {
+ int rc = SQLITE_OK;
+ if (p != null && p.inTrans == TRANS_WRITE) {
+ BtShared pBt = p.pBt;
+ Debug.Assert(op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK);
+ Debug.Assert(iSavepoint >= 0 || (iSavepoint == -1 && op == SAVEPOINT_ROLLBACK));
+ sqlite3BtreeEnter(p);
+ rc = sqlite3PagerSavepoint(pBt.pPager, op, iSavepoint);
+ if (rc == SQLITE_OK) {
+ if (iSavepoint < 0 && pBt.initiallyEmpty)
+ pBt.nPage = 0;
+ rc = newDatabase(pBt);
+ pBt.nPage = sqlite3Get4byte(pBt.pPage1.aData, 28);
+ /* The database size was written into the offset 28 of the header
+ ** when the transaction started, so we know that the value at offset
+ ** 28 is nonzero. */
+ Debug.Assert(pBt.nPage > 0);
+ }
+ sqlite3BtreeLeave(p);
+ }
+ return rc;
+ }
-/*
-** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
-** or SAVEPOINT_RELEASE. This function either releases or rolls back the
-** savepoint identified by parameter iSavepoint, depending on the value
-** of op.
-**
-** Normally, iSavepoint is greater than or equal to zero. However, if op is
-** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
-** contents of the entire transaction are rolled back. This is different
-** from a normal transaction rollback, as no locks are released and the
-** transaction remains open.
-*/
-static int sqlite3BtreeSavepoint( Btree p, int op, int iSavepoint )
-{
- int rc = SQLITE_OK;
- if ( p != null && p.inTrans == TRANS_WRITE )
- {
- BtShared pBt = p.pBt;
- Debug.Assert( op == SAVEPOINT_RELEASE || op == SAVEPOINT_ROLLBACK );
- Debug.Assert( iSavepoint >= 0 || ( iSavepoint == -1 && op == SAVEPOINT_ROLLBACK ) );
- sqlite3BtreeEnter( p );
- rc = sqlite3PagerSavepoint( pBt.pPager, op, iSavepoint );
- if ( rc == SQLITE_OK )
- {
- if ( iSavepoint < 0 && pBt.initiallyEmpty )
- pBt.nPage = 0;
- rc = newDatabase( pBt );
- pBt.nPage = sqlite3Get4byte( pBt.pPage1.aData, 28 );
- /* The database size was written into the offset 28 of the header
- ** when the transaction started, so we know that the value at offset
- ** 28 is nonzero. */
- Debug.Assert( pBt.nPage > 0 );
- }
- sqlite3BtreeLeave( p );
- }
- return rc;
-}
+ /*
+ ** Create a new cursor for the BTree whose root is on the page
+ ** iTable. If a read-only cursor is requested, it is assumed that
+ ** the caller already has at least a read-only transaction open
+ ** on the database already. If a write-cursor is requested, then
+ ** the caller is assumed to have an open write transaction.
+ **
+ ** If wrFlag==null, then the cursor can only be used for reading.
+ ** If wrFlag==1, then the cursor can be used for reading or for
+ ** writing if other conditions for writing are also met. These
+ ** are the conditions that must be met in order for writing to
+ ** be allowed:
+ **
+ ** 1: The cursor must have been opened with wrFlag==1
+ **
+ ** 2: Other database connections that share the same pager cache
+ ** but which are not in the READ_UNCOMMITTED state may not have
+ ** cursors open with wrFlag==null on the same table. Otherwise
+ ** the changes made by this write cursor would be visible to
+ ** the read cursors in the other database connection.
+ **
+ ** 3: The database must be writable (not on read-only media)
+ **
+ ** 4: There must be an active transaction.
+ **
+ ** No checking is done to make sure that page iTable really is the
+ ** root page of a b-tree. If it is not, then the cursor acquired
+ ** will not work correctly.
+ **
+ ** It is assumed that the sqlite3BtreeCursorZero() has been called
+ ** on pCur to initialize the memory space prior to invoking this routine.
+ */
+ static int btreeCursor(
+ Btree p, /* The btree */
+ int iTable, /* Root page of table to open */
+ int wrFlag, /* 1 to write. 0 read-only */
+ KeyInfo pKeyInfo, /* First arg to comparison function */
+ BtCursor pCur /* Space for new cursor */
+ ) {
+ BtShared pBt = p.pBt; /* Shared b-tree handle */
+
+ Debug.Assert(sqlite3BtreeHoldsMutex(p));
+ Debug.Assert(wrFlag == 0 || wrFlag == 1);
+
+ /* The following Debug.Assert statements verify that if this is a sharable
+ ** b-tree database, the connection is holding the required table locks,
+ ** and that no other connection has any open cursor that conflicts with
+ ** this lock. */
+ Debug.Assert(hasSharedCacheTableLock(p, (u32)iTable, pKeyInfo != null ? 1 : 0, wrFlag + 1));
+ Debug.Assert(wrFlag == 0 || !hasReadConflicts(p, (u32)iTable));
+
+ /* Assert that the caller has opened the required transaction. */
+ Debug.Assert(p.inTrans > TRANS_NONE);
+ Debug.Assert(wrFlag == 0 || p.inTrans == TRANS_WRITE);
+ Debug.Assert(pBt.pPage1 != null && pBt.pPage1.aData != null);
+
+ if (NEVER(wrFlag != 0 && pBt.readOnly)) {
+ return SQLITE_READONLY;
+ }
+ if (iTable == 1 && btreePagecount(pBt) == 0) {
+ return SQLITE_EMPTY;
+ }
-/*
-** Create a new cursor for the BTree whose root is on the page
-** iTable. If a read-only cursor is requested, it is assumed that
-** the caller already has at least a read-only transaction open
-** on the database already. If a write-cursor is requested, then
-** the caller is assumed to have an open write transaction.
-**
-** If wrFlag==null, then the cursor can only be used for reading.
-** If wrFlag==1, then the cursor can be used for reading or for
-** writing if other conditions for writing are also met. These
-** are the conditions that must be met in order for writing to
-** be allowed:
-**
-** 1: The cursor must have been opened with wrFlag==1
-**
-** 2: Other database connections that share the same pager cache
-** but which are not in the READ_UNCOMMITTED state may not have
-** cursors open with wrFlag==null on the same table. Otherwise
-** the changes made by this write cursor would be visible to
-** the read cursors in the other database connection.
-**
-** 3: The database must be writable (not on read-only media)
-**
-** 4: There must be an active transaction.
-**
-** No checking is done to make sure that page iTable really is the
-** root page of a b-tree. If it is not, then the cursor acquired
-** will not work correctly.
-**
-** It is assumed that the sqlite3BtreeCursorZero() has been called
-** on pCur to initialize the memory space prior to invoking this routine.
-*/
-static int btreeCursor(
-Btree p, /* The btree */
-int iTable, /* Root page of table to open */
-int wrFlag, /* 1 to write. 0 read-only */
-KeyInfo pKeyInfo, /* First arg to comparison function */
-BtCursor pCur /* Space for new cursor */
-)
-{
- BtShared pBt = p.pBt; /* Shared b-tree handle */
-
- Debug.Assert( sqlite3BtreeHoldsMutex( p ) );
- Debug.Assert( wrFlag == 0 || wrFlag == 1 );
-
- /* The following Debug.Assert statements verify that if this is a sharable
- ** b-tree database, the connection is holding the required table locks,
- ** and that no other connection has any open cursor that conflicts with
- ** this lock. */
- Debug.Assert( hasSharedCacheTableLock( p, (u32)iTable, pKeyInfo != null ? 1 : 0, wrFlag + 1 ) );
- Debug.Assert( wrFlag == 0 || !hasReadConflicts( p, (u32)iTable ) );
-
- /* Assert that the caller has opened the required transaction. */
- Debug.Assert( p.inTrans > TRANS_NONE );
- Debug.Assert( wrFlag == 0 || p.inTrans == TRANS_WRITE );
- Debug.Assert( pBt.pPage1 != null && pBt.pPage1.aData != null );
-
- if ( NEVER( wrFlag != 0 && pBt.readOnly ) )
- {
- return SQLITE_READONLY;
- }
- if ( iTable == 1 && btreePagecount( pBt ) == 0 )
- {
- return SQLITE_EMPTY;
- }
-
- /* Now that no other errors can occur, finish filling in the BtCursor
- ** variables and link the cursor into the BtShared list. */
- pCur.pgnoRoot = (Pgno)iTable;
- pCur.iPage = -1;
- pCur.pKeyInfo = pKeyInfo;
- pCur.pBtree = p;
- pCur.pBt = pBt;
- pCur.wrFlag = (u8)wrFlag;
- pCur.pNext = pBt.pCursor;
- if ( pCur.pNext != null )
- {
- pCur.pNext.pPrev = pCur;
- }
- pBt.pCursor = pCur;
- pCur.eState = CURSOR_INVALID;
- pCur.cachedRowid = 0;
- return SQLITE_OK;
-}
-static int sqlite3BtreeCursor(
-Btree p, /* The btree */
-int iTable, /* Root page of table to open */
-int wrFlag, /* 1 to write. 0 read-only */
-KeyInfo pKeyInfo, /* First arg to xCompare() */
-BtCursor pCur /* Write new cursor here */
-)
-{
- int rc;
- sqlite3BtreeEnter( p );
- rc = btreeCursor( p, iTable, wrFlag, pKeyInfo, pCur );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /* Now that no other errors can occur, finish filling in the BtCursor
+ ** variables and link the cursor into the BtShared list. */
+ pCur.pgnoRoot = (Pgno)iTable;
+ pCur.iPage = -1;
+ pCur.pKeyInfo = pKeyInfo;
+ pCur.pBtree = p;
+ pCur.pBt = pBt;
+ pCur.wrFlag = (u8)wrFlag;
+ pCur.pNext = pBt.pCursor;
+ if (pCur.pNext != null) {
+ pCur.pNext.pPrev = pCur;
+ }
+ pBt.pCursor = pCur;
+ pCur.eState = CURSOR_INVALID;
+ pCur.cachedRowid = 0;
+ return SQLITE_OK;
+ }
+ static int sqlite3BtreeCursor(
+ Btree p, /* The btree */
+ int iTable, /* Root page of table to open */
+ int wrFlag, /* 1 to write. 0 read-only */
+ KeyInfo pKeyInfo, /* First arg to xCompare() */
+ BtCursor pCur /* Write new cursor here */
+ ) {
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** Return the size of a BtCursor object in bytes.
-**
-** This interfaces is needed so that users of cursors can preallocate
-** sufficient storage to hold a cursor. The BtCursor object is opaque
-** to users so they cannot do the sizeof() themselves - they must call
-** this routine.
-*/
-static int sqlite3BtreeCursorSize()
-{
- return -1; // Not Used -- return ROUND8(sizeof(BtCursor));
-}
+ /*
+ ** Return the size of a BtCursor object in bytes.
+ **
+ ** This interfaces is needed so that users of cursors can preallocate
+ ** sufficient storage to hold a cursor. The BtCursor object is opaque
+ ** to users so they cannot do the sizeof() themselves - they must call
+ ** this routine.
+ */
+ static int sqlite3BtreeCursorSize() {
+ return -1; // Not Used -- return ROUND8(sizeof(BtCursor));
+ }
-/*
-** Initialize memory that will be converted into a BtCursor object.
-**
-** The simple approach here would be to memset() the entire object
-** to zero. But it turns out that the apPage[] and aiIdx[] arrays
-** do not need to be zeroed and they are large, so we can save a lot
-** of run-time by skipping the initialization of those elements.
-*/
-static void sqlite3BtreeCursorZero( BtCursor p )
-{
- p.Clear(); // memset( p, 0, offsetof( BtCursor, iPage ) );
-}
+ /*
+ ** Initialize memory that will be converted into a BtCursor object.
+ **
+ ** The simple approach here would be to memset() the entire object
+ ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
+ ** do not need to be zeroed and they are large, so we can save a lot
+ ** of run-time by skipping the initialization of those elements.
+ */
+ static void sqlite3BtreeCursorZero(BtCursor p) {
+ p.Clear(); // memset( p, 0, offsetof( BtCursor, iPage ) );
+ }
-/*
-** Set the cached rowid value of every cursor in the same database file
-** as pCur and having the same root page number as pCur. The value is
-** set to iRowid.
-**
-** Only positive rowid values are considered valid for this cache.
-** The cache is initialized to zero, indicating an invalid cache.
-** A btree will work fine with zero or negative rowids. We just cannot
-** cache zero or negative rowids, which means tables that use zero or
-** negative rowids might run a little slower. But in practice, zero
-** or negative rowids are very uncommon so this should not be a problem.
-*/
-static void sqlite3BtreeSetCachedRowid( BtCursor pCur, sqlite3_int64 iRowid )
-{
- BtCursor p;
- for ( p = pCur.pBt.pCursor; p != null; p = p.pNext )
- {
- if ( p.pgnoRoot == pCur.pgnoRoot )
- p.cachedRowid = iRowid;
- }
- Debug.Assert( pCur.cachedRowid == iRowid );
-}
+ /*
+ ** Set the cached rowid value of every cursor in the same database file
+ ** as pCur and having the same root page number as pCur. The value is
+ ** set to iRowid.
+ **
+ ** Only positive rowid values are considered valid for this cache.
+ ** The cache is initialized to zero, indicating an invalid cache.
+ ** A btree will work fine with zero or negative rowids. We just cannot
+ ** cache zero or negative rowids, which means tables that use zero or
+ ** negative rowids might run a little slower. But in practice, zero
+ ** or negative rowids are very uncommon so this should not be a problem.
+ */
+ static void sqlite3BtreeSetCachedRowid(BtCursor pCur, sqlite3_int64 iRowid) {
+ BtCursor p;
+ for (p = pCur.pBt.pCursor; p != null; p = p.pNext) {
+ if (p.pgnoRoot == pCur.pgnoRoot)
+ p.cachedRowid = iRowid;
+ }
+ Debug.Assert(pCur.cachedRowid == iRowid);
+ }
-/*
-** Return the cached rowid for the given cursor. A negative or zero
-** return value indicates that the rowid cache is invalid and should be
-** ignored. If the rowid cache has never before been set, then a
-** zero is returned.
-*/
-static sqlite3_int64 sqlite3BtreeGetCachedRowid( BtCursor pCur )
-{
- return pCur.cachedRowid;
-}
+ /*
+ ** Return the cached rowid for the given cursor. A negative or zero
+ ** return value indicates that the rowid cache is invalid and should be
+ ** ignored. If the rowid cache has never before been set, then a
+ ** zero is returned.
+ */
+ static sqlite3_int64 sqlite3BtreeGetCachedRowid(BtCursor pCur) {
+ return pCur.cachedRowid;
+ }
-/*
-** Close a cursor. The read lock on the database file is released
-** when the last cursor is closed.
-*/
-static int sqlite3BtreeCloseCursor( BtCursor pCur )
-{
- Btree pBtree = pCur.pBtree;
- if ( pBtree != null )
- {
- int i;
- BtShared pBt = pCur.pBt;
- sqlite3BtreeEnter( pBtree );
- sqlite3BtreeClearCursor( pCur );
- if ( pCur.pPrev != null )
- {
- pCur.pPrev.pNext = pCur.pNext;
- }
- else
- {
- pBt.pCursor = pCur.pNext;
- }
- if ( pCur.pNext != null )
- {
- pCur.pNext.pPrev = pCur.pPrev;
- }
- for ( i = 0; i <= pCur.iPage; i++ )
- {
- releasePage( pCur.apPage[i] );
- }
- unlockBtreeIfUnused( pBt );
- invalidateOverflowCache( pCur );
- /* sqlite3_free(ref pCur); */
- sqlite3BtreeLeave( pBtree );
- }
- return SQLITE_OK;
-}
+ /*
+ ** Close a cursor. The read lock on the database file is released
+ ** when the last cursor is closed.
+ */
+ static int sqlite3BtreeCloseCursor(BtCursor pCur) {
+ Btree pBtree = pCur.pBtree;
+ if (pBtree != null) {
+ int i;
+ BtShared pBt = pCur.pBt;
+ sqlite3BtreeEnter(pBtree);
+ sqlite3BtreeClearCursor(pCur);
+ if (pCur.pPrev != null) {
+ pCur.pPrev.pNext = pCur.pNext;
+ } else {
+ pBt.pCursor = pCur.pNext;
+ }
+ if (pCur.pNext != null) {
+ pCur.pNext.pPrev = pCur.pPrev;
+ }
+ for (i = 0; i <= pCur.iPage; i++) {
+ releasePage(pCur.apPage[i]);
+ }
+ unlockBtreeIfUnused(pBt);
+ invalidateOverflowCache(pCur);
+ /* sqlite3_free(ref pCur); */
+ sqlite3BtreeLeave(pBtree);
+ }
+ return SQLITE_OK;
+ }
-/*
-** Make sure the BtCursor* given in the argument has a valid
-** BtCursor.info structure. If it is not already valid, call
-** btreeParseCell() to fill it in.
-**
-** BtCursor.info is a cache of the information in the current cell.
-** Using this cache reduces the number of calls to btreeParseCell().
-**
-** 2007-06-25: There is a bug in some versions of MSVC that cause the
-** compiler to crash when getCellInfo() is implemented as a macro.
-** But there is a measureable speed advantage to using the macro on gcc
-** (when less compiler optimizations like -Os or -O0 are used and the
-** compiler is not doing agressive inlining.) So we use a real function
-** for MSVC and a macro for everything else. Ticket #2457.
-*/
+ /*
+ ** Make sure the BtCursor* given in the argument has a valid
+ ** BtCursor.info structure. If it is not already valid, call
+ ** btreeParseCell() to fill it in.
+ **
+ ** BtCursor.info is a cache of the information in the current cell.
+ ** Using this cache reduces the number of calls to btreeParseCell().
+ **
+ ** 2007-06-25: There is a bug in some versions of MSVC that cause the
+ ** compiler to crash when getCellInfo() is implemented as a macro.
+ ** But there is a measureable speed advantage to using the macro on gcc
+ ** (when less compiler optimizations like -Os or -O0 are used and the
+ ** compiler is not doing agressive inlining.) So we use a real function
+ ** for MSVC and a macro for everything else. Ticket #2457.
+ */
#if !NDEBUG
-static void assertCellInfo( BtCursor pCur )
-{
- CellInfo info;
- int iPage = pCur.iPage;
- info = new CellInfo();//memset(info, 0, sizeof(info));
- btreeParseCell( pCur.apPage[iPage], pCur.aiIdx[iPage], ref info );
- Debug.Assert( info.GetHashCode() == pCur.info.GetHashCode() || info.Equals( pCur.info ) );//memcmp(info, pCur.info, sizeof(info))==0 );
-}
+ static void assertCellInfo(BtCursor pCur) {
+ CellInfo info;
+ int iPage = pCur.iPage;
+ info = new CellInfo();//memset(info, 0, sizeof(info));
+ btreeParseCell(pCur.apPage[iPage], pCur.aiIdx[iPage], ref info);
+ Debug.Assert(info.GetHashCode() == pCur.info.GetHashCode() || info.Equals(pCur.info));//memcmp(info, pCur.info, sizeof(info))==0 );
+ }
#else
// #define assertCellInfo(x)
static void assertCellInfo(BtCursor pCur) { }
#endif
#if _MSC_VER
-/* Use a real function in MSVC to work around bugs in that compiler. */
-static void getCellInfo( BtCursor pCur )
-{
- if ( pCur.info.nSize == 0 )
- {
- int iPage = pCur.iPage;
- btreeParseCell( pCur.apPage[iPage], pCur.aiIdx[iPage], ref pCur.info );
- pCur.validNKey = true;
- }
- else
- {
- assertCellInfo( pCur );
- }
-}
+ /* Use a real function in MSVC to work around bugs in that compiler. */
+ static void getCellInfo(BtCursor pCur) {
+ if (pCur.info.nSize == 0) {
+ int iPage = pCur.iPage;
+ btreeParseCell(pCur.apPage[iPage], pCur.aiIdx[iPage], ref pCur.info);
+ pCur.validNKey = true;
+ } else {
+ assertCellInfo(pCur);
+ }
+ }
#else //* if not _MSC_VER */
/* Use a macro in all other compilers so that the function is inlined */
//#define getCellInfo(pCur) \
@@ -4169,299 +3825,271 @@ static void getCellInfo( BtCursor pCur )
#endif //* _MSC_VER */
#if !NDEBUG //* The next routine used only within Debug.Assert() statements */
-/*
-** Return true if the given BtCursor is valid. A valid cursor is one
-** that is currently pointing to a row in a (non-empty) table.
-** This is a verification routine is used only within Debug.Assert() statements.
-*/
-static bool sqlite3BtreeCursorIsValid( BtCursor pCur )
-{
- return pCur != null && pCur.eState == CURSOR_VALID;
-}
+ /*
+ ** Return true if the given BtCursor is valid. A valid cursor is one
+ ** that is currently pointing to a row in a (non-empty) table.
+ ** This is a verification routine is used only within Debug.Assert() statements.
+ */
+ static bool sqlite3BtreeCursorIsValid(BtCursor pCur) {
+ return pCur != null && pCur.eState == CURSOR_VALID;
+ }
#else
static bool sqlite3BtreeCursorIsValid(BtCursor pCur) { return true; }
#endif //* NDEBUG */
-/*
-** Set pSize to the size of the buffer needed to hold the value of
-** the key for the current entry. If the cursor is not pointing
-** to a valid entry, pSize is set to 0.
-**
-** For a table with the INTKEY flag set, this routine returns the key
-** itself, not the number of bytes in the key.
-**
-** The caller must position the cursor prior to invoking this routine.
-**
-** This routine cannot fail. It always returns SQLITE_OK.
-*/
-static int sqlite3BtreeKeySize( BtCursor pCur, ref i64 pSize )
-{
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_INVALID || pCur.eState == CURSOR_VALID );
- if ( pCur.eState != CURSOR_VALID )
- {
- pSize = 0;
- }
- else
- {
- getCellInfo( pCur );
- pSize = pCur.info.nKey;
- }
- return SQLITE_OK;
-}
-
-/*
-** Set pSize to the number of bytes of data in the entry the
-** cursor currently points to.
-**
-** The caller must guarantee that the cursor is pointing to a non-NULL
-** valid entry. In other words, the calling procedure must guarantee
-** that the cursor has Cursor.eState==CURSOR_VALID.
-**
-** Failure is not possible. This function always returns SQLITE_OK.
-** It might just as well be a procedure (returning void) but we continue
-** to return an integer result code for historical reasons.
-*/
-static int sqlite3BtreeDataSize( BtCursor pCur, ref u32 pSize )
-{
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- getCellInfo( pCur );
- pSize = pCur.info.nData;
- return SQLITE_OK;
-}
+ /*
+ ** Set pSize to the size of the buffer needed to hold the value of
+ ** the key for the current entry. If the cursor is not pointing
+ ** to a valid entry, pSize is set to 0.
+ **
+ ** For a table with the INTKEY flag set, this routine returns the key
+ ** itself, not the number of bytes in the key.
+ **
+ ** The caller must position the cursor prior to invoking this routine.
+ **
+ ** This routine cannot fail. It always returns SQLITE_OK.
+ */
+ static int sqlite3BtreeKeySize(BtCursor pCur, ref i64 pSize) {
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_INVALID || pCur.eState == CURSOR_VALID);
+ if (pCur.eState != CURSOR_VALID) {
+ pSize = 0;
+ } else {
+ getCellInfo(pCur);
+ pSize = pCur.info.nKey;
+ }
+ return SQLITE_OK;
+ }
-/*
-** Given the page number of an overflow page in the database (parameter
-** ovfl), this function finds the page number of the next page in the
-** linked list of overflow pages. If possible, it uses the auto-vacuum
-** pointer-map data instead of reading the content of page ovfl to do so.
-**
-** If an error occurs an SQLite error code is returned. Otherwise:
-**
-** The page number of the next overflow page in the linked list is
-** written to pPgnoNext. If page ovfl is the last page in its linked
-** list, pPgnoNext is set to zero.
-**
-** If ppPage is not NULL, and a reference to the MemPage object corresponding
-** to page number pOvfl was obtained, then ppPage is set to point to that
-** reference. It is the responsibility of the caller to call releasePage()
-** on ppPage to free the reference. In no reference was obtained (because
-** the pointer-map was used to obtain the value for pPgnoNext), then
-** ppPage is set to zero.
-*/
-static int getOverflowPage(
-BtShared pBt, /* The database file */
-Pgno ovfl, /* Current overflow page number */
-out MemPage ppPage, /* OUT: MemPage handle (may be NULL) */
-out Pgno pPgnoNext /* OUT: Next overflow page number */
-)
-{
- Pgno next = 0;
- MemPage pPage = null;
- ppPage = null;
- int rc = SQLITE_OK;
+ /*
+ ** Set pSize to the number of bytes of data in the entry the
+ ** cursor currently points to.
+ **
+ ** The caller must guarantee that the cursor is pointing to a non-NULL
+ ** valid entry. In other words, the calling procedure must guarantee
+ ** that the cursor has Cursor.eState==CURSOR_VALID.
+ **
+ ** Failure is not possible. This function always returns SQLITE_OK.
+ ** It might just as well be a procedure (returning void) but we continue
+ ** to return an integer result code for historical reasons.
+ */
+ static int sqlite3BtreeDataSize(BtCursor pCur, ref u32 pSize) {
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ getCellInfo(pCur);
+ pSize = pCur.info.nData;
+ return SQLITE_OK;
+ }
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- // Debug.Assert( pPgnoNext);
+ /*
+ ** Given the page number of an overflow page in the database (parameter
+ ** ovfl), this function finds the page number of the next page in the
+ ** linked list of overflow pages. If possible, it uses the auto-vacuum
+ ** pointer-map data instead of reading the content of page ovfl to do so.
+ **
+ ** If an error occurs an SQLite error code is returned. Otherwise:
+ **
+ ** The page number of the next overflow page in the linked list is
+ ** written to pPgnoNext. If page ovfl is the last page in its linked
+ ** list, pPgnoNext is set to zero.
+ **
+ ** If ppPage is not NULL, and a reference to the MemPage object corresponding
+ ** to page number pOvfl was obtained, then ppPage is set to point to that
+ ** reference. It is the responsibility of the caller to call releasePage()
+ ** on ppPage to free the reference. In no reference was obtained (because
+ ** the pointer-map was used to obtain the value for pPgnoNext), then
+ ** ppPage is set to zero.
+ */
+ static int getOverflowPage(
+ BtShared pBt, /* The database file */
+ Pgno ovfl, /* Current overflow page number */
+ out MemPage ppPage, /* OUT: MemPage handle (may be NULL) */
+ out Pgno pPgnoNext /* OUT: Next overflow page number */
+ ) {
+ Pgno next = 0;
+ MemPage pPage = null;
+ ppPage = null;
+ int rc = SQLITE_OK;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ // Debug.Assert( pPgnoNext);
#if !SQLITE_OMIT_AUTOVACUUM
- /* Try to find the next page in the overflow list using the
-** autovacuum pointer-map pages. Guess that the next page in
-** the overflow list is page number (ovfl+1). If that guess turns
-** out to be wrong, fall back to loading the data of page
-** number ovfl to determine the next page number.
-*/
- if ( pBt.autoVacuum )
- {
- Pgno pgno = 0;
- Pgno iGuess = ovfl + 1;
- u8 eType = 0;
-
- while ( PTRMAP_ISPAGE( pBt, iGuess ) || iGuess == PENDING_BYTE_PAGE( pBt ) )
- {
- iGuess++;
- }
-
- if ( iGuess <= btreePagecount( pBt ) )
- {
- rc = ptrmapGet( pBt, iGuess, ref eType, ref pgno );
- if ( rc == SQLITE_OK && eType == PTRMAP_OVERFLOW2 && pgno == ovfl )
- {
- next = iGuess;
- rc = SQLITE_DONE;
- }
- }
- }
+ /* Try to find the next page in the overflow list using the
+ ** autovacuum pointer-map pages. Guess that the next page in
+ ** the overflow list is page number (ovfl+1). If that guess turns
+ ** out to be wrong, fall back to loading the data of page
+ ** number ovfl to determine the next page number.
+ */
+ if (pBt.autoVacuum) {
+ Pgno pgno = 0;
+ Pgno iGuess = ovfl + 1;
+ u8 eType = 0;
+
+ while (PTRMAP_ISPAGE(pBt, iGuess) || iGuess == PENDING_BYTE_PAGE(pBt)) {
+ iGuess++;
+ }
+
+ if (iGuess <= btreePagecount(pBt)) {
+ rc = ptrmapGet(pBt, iGuess, ref eType, ref pgno);
+ if (rc == SQLITE_OK && eType == PTRMAP_OVERFLOW2 && pgno == ovfl) {
+ next = iGuess;
+ rc = SQLITE_DONE;
+ }
+ }
+ }
#endif
- Debug.Assert( next == 0 || rc == SQLITE_DONE );
- if ( rc == SQLITE_OK )
- {
- rc = btreeGetPage( pBt, ovfl, ref pPage, 0 );
- Debug.Assert( rc == SQLITE_OK || pPage == null );
- if ( rc == SQLITE_OK )
- {
- next = sqlite3Get4byte( pPage.aData );
- }
- }
-
- pPgnoNext = next;
- if ( ppPage != null )
- {
- ppPage = pPage;
- }
- else
- {
- releasePage( pPage );
- }
- return ( rc == SQLITE_DONE ? SQLITE_OK : rc );
-}
+ Debug.Assert(next == 0 || rc == SQLITE_DONE);
+ if (rc == SQLITE_OK) {
+ rc = btreeGetPage(pBt, ovfl, ref pPage, 0);
+ Debug.Assert(rc == SQLITE_OK || pPage == null);
+ if (rc == SQLITE_OK) {
+ next = sqlite3Get4byte(pPage.aData);
+ }
+ }
-/*
-** Copy data from a buffer to a page, or from a page to a buffer.
-**
-** pPayload is a pointer to data stored on database page pDbPage.
-** If argument eOp is false, then nByte bytes of data are copied
-** from pPayload to the buffer pointed at by pBuf. If eOp is true,
-** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
-** of data are copied from the buffer pBuf to pPayload.
-**
-** SQLITE_OK is returned on success, otherwise an error code.
-*/
-static int copyPayload(
-byte[] pPayload, /* Pointer to page data */
-u32 payloadOffset, /* Offset into page data */
-byte[] pBuf, /* Pointer to buffer */
-u32 pBufOffset, /* Offset into buffer */
-u32 nByte, /* Number of bytes to copy */
-int eOp, /* 0 . copy from page, 1 . copy to page */
-DbPage pDbPage /* Page containing pPayload */
-)
-{
- if ( eOp != 0 )
- {
- /* Copy data from buffer to page (a write operation) */
- int rc = sqlite3PagerWrite( pDbPage );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- Buffer.BlockCopy( pBuf, (int)pBufOffset, pPayload, (int)payloadOffset, (int)nByte );// memcpy( pPayload, pBuf, nByte );
- }
- else
- {
- /* Copy data from page to buffer (a read operation) */
- Buffer.BlockCopy( pPayload, (int)payloadOffset, pBuf, (int)pBufOffset, (int)nByte );//memcpy(pBuf, pPayload, nByte);
- }
- return SQLITE_OK;
-}
-//static int copyPayload(
-// byte[] pPayload, /* Pointer to page data */
-// byte[] pBuf, /* Pointer to buffer */
-// int nByte, /* Number of bytes to copy */
-// int eOp, /* 0 -> copy from page, 1 -> copy to page */
-// DbPage pDbPage /* Page containing pPayload */
-//){
-// if( eOp!=0 ){
-// /* Copy data from buffer to page (a write operation) */
-// int rc = sqlite3PagerWrite(pDbPage);
-// if( rc!=SQLITE_OK ){
-// return rc;
-// }
-// memcpy(pPayload, pBuf, nByte);
-// }else{
-// /* Copy data from page to buffer (a read operation) */
-// memcpy(pBuf, pPayload, nByte);
-// }
-// return SQLITE_OK;
-//}
+ pPgnoNext = next;
+ if (ppPage != null) {
+ ppPage = pPage;
+ } else {
+ releasePage(pPage);
+ }
+ return (rc == SQLITE_DONE ? SQLITE_OK : rc);
+ }
-/*
-** This function is used to read or overwrite payload information
-** for the entry that the pCur cursor is pointing to. If the eOp
-** parameter is 0, this is a read operation (data copied into
-** buffer pBuf). If it is non-zero, a write (data copied from
-** buffer pBuf).
-**
-** A total of "amt" bytes are read or written beginning at "offset".
-** Data is read to or from the buffer pBuf.
-**
-** The content being read or written might appear on the main page
-** or be scattered out on multiple overflow pages.
-**
-** If the BtCursor.isIncrblobHandle flag is set, and the current
-** cursor entry uses one or more overflow pages, this function
-** allocates space for and lazily popluates the overflow page-list
-** cache array (BtCursor.aOverflow). Subsequent calls use this
-** cache to make seeking to the supplied offset more efficient.
-**
-** Once an overflow page-list cache has been allocated, it may be
-** invalidated if some other cursor writes to the same table, or if
-** the cursor is moved to a different row. Additionally, in auto-vacuum
-** mode, the following events may invalidate an overflow page-list cache.
-**
-** * An incremental vacuum,
-** * A commit in auto_vacuum="full" mode,
-** * Creating a table (may require moving an overflow page).
-*/
-static int accessPayload(
-BtCursor pCur, /* Cursor pointing to entry to read from */
-u32 offset, /* Begin reading this far into payload */
-u32 amt, /* Read this many bytes */
-byte[] pBuf, /* Write the bytes into this buffer */
-int eOp /* zero to read. non-zero to write. */
-)
-{
- u32 pBufOffset = 0;
- byte[] aPayload;
- int rc = SQLITE_OK;
- u32 nKey;
- int iIdx = 0;
- MemPage pPage = pCur.apPage[pCur.iPage]; /* Btree page of current entry */
- BtShared pBt = pCur.pBt; /* Btree this cursor belongs to */
-
- Debug.Assert( pPage != null );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- Debug.Assert( pCur.aiIdx[pCur.iPage] < pPage.nCell );
- Debug.Assert( cursorHoldsMutex( pCur ) );
-
- getCellInfo( pCur );
- aPayload = pCur.info.pCell; //pCur.info.pCell + pCur.info.nHeader;
- nKey = (u32)( pPage.intKey != 0 ? 0 : (int)pCur.info.nKey );
-
- if ( NEVER( offset + amt > nKey + pCur.info.nData )
- || pCur.info.nLocal > pBt.usableSize//&aPayload[pCur.info.nLocal] > &pPage.aData[pBt.usableSize]
- )
- {
- /* Trying to read or write past the end of the data is an error */
- return SQLITE_CORRUPT_BKPT();
- }
-
- /* Check if data must be read/written to/from the btree page itself. */
- if ( offset < pCur.info.nLocal )
- {
- int a = (int)amt;
- if ( a + offset > pCur.info.nLocal )
- {
- a = (int)( pCur.info.nLocal - offset );
- }
- rc = copyPayload( aPayload, (u32)( offset + pCur.info.iCell + pCur.info.nHeader ), pBuf, pBufOffset, (u32)a, eOp, pPage.pDbPage );
- offset = 0;
- pBufOffset += (u32)a; //pBuf += a;
- amt -= (u32)a;
- }
- else
- {
- offset -= pCur.info.nLocal;
- }
-
- if ( rc == SQLITE_OK && amt > 0 )
- {
- u32 ovflSize = (u32)( pBt.usableSize - 4 ); /* Bytes content per ovfl page */
- Pgno nextPage;
-
- nextPage = sqlite3Get4byte( aPayload, pCur.info.nLocal + pCur.info.iCell + pCur.info.nHeader );
+ /*
+ ** Copy data from a buffer to a page, or from a page to a buffer.
+ **
+ ** pPayload is a pointer to data stored on database page pDbPage.
+ ** If argument eOp is false, then nByte bytes of data are copied
+ ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
+ ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
+ ** of data are copied from the buffer pBuf to pPayload.
+ **
+ ** SQLITE_OK is returned on success, otherwise an error code.
+ */
+ static int copyPayload(
+ byte[] pPayload, /* Pointer to page data */
+ u32 payloadOffset, /* Offset into page data */
+ byte[] pBuf, /* Pointer to buffer */
+ u32 pBufOffset, /* Offset into buffer */
+ u32 nByte, /* Number of bytes to copy */
+ int eOp, /* 0 . copy from page, 1 . copy to page */
+ DbPage pDbPage /* Page containing pPayload */
+ ) {
+ if (eOp != 0) {
+ /* Copy data from buffer to page (a write operation) */
+ int rc = sqlite3PagerWrite(pDbPage);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ Buffer.BlockCopy(pBuf, (int)pBufOffset, pPayload, (int)payloadOffset, (int)nByte);// memcpy( pPayload, pBuf, nByte );
+ } else {
+ /* Copy data from page to buffer (a read operation) */
+ Buffer.BlockCopy(pPayload, (int)payloadOffset, pBuf, (int)pBufOffset, (int)nByte);//memcpy(pBuf, pPayload, nByte);
+ }
+ return SQLITE_OK;
+ }
+ //static int copyPayload(
+ // byte[] pPayload, /* Pointer to page data */
+ // byte[] pBuf, /* Pointer to buffer */
+ // int nByte, /* Number of bytes to copy */
+ // int eOp, /* 0 -> copy from page, 1 -> copy to page */
+ // DbPage pDbPage /* Page containing pPayload */
+ //){
+ // if( eOp!=0 ){
+ // /* Copy data from buffer to page (a write operation) */
+ // int rc = sqlite3PagerWrite(pDbPage);
+ // if( rc!=SQLITE_OK ){
+ // return rc;
+ // }
+ // memcpy(pPayload, pBuf, nByte);
+ // }else{
+ // /* Copy data from page to buffer (a read operation) */
+ // memcpy(pBuf, pPayload, nByte);
+ // }
+ // return SQLITE_OK;
+ //}
+
+ /*
+ ** This function is used to read or overwrite payload information
+ ** for the entry that the pCur cursor is pointing to. If the eOp
+ ** parameter is 0, this is a read operation (data copied into
+ ** buffer pBuf). If it is non-zero, a write (data copied from
+ ** buffer pBuf).
+ **
+ ** A total of "amt" bytes are read or written beginning at "offset".
+ ** Data is read to or from the buffer pBuf.
+ **
+ ** The content being read or written might appear on the main page
+ ** or be scattered out on multiple overflow pages.
+ **
+ ** If the BtCursor.isIncrblobHandle flag is set, and the current
+ ** cursor entry uses one or more overflow pages, this function
+ ** allocates space for and lazily popluates the overflow page-list
+ ** cache array (BtCursor.aOverflow). Subsequent calls use this
+ ** cache to make seeking to the supplied offset more efficient.
+ **
+ ** Once an overflow page-list cache has been allocated, it may be
+ ** invalidated if some other cursor writes to the same table, or if
+ ** the cursor is moved to a different row. Additionally, in auto-vacuum
+ ** mode, the following events may invalidate an overflow page-list cache.
+ **
+ ** * An incremental vacuum,
+ ** * A commit in auto_vacuum="full" mode,
+ ** * Creating a table (may require moving an overflow page).
+ */
+ static int accessPayload(
+ BtCursor pCur, /* Cursor pointing to entry to read from */
+ u32 offset, /* Begin reading this far into payload */
+ u32 amt, /* Read this many bytes */
+ byte[] pBuf, /* Write the bytes into this buffer */
+ int eOp /* zero to read. non-zero to write. */
+ ) {
+ u32 pBufOffset = 0;
+ byte[] aPayload;
+ int rc = SQLITE_OK;
+ u32 nKey;
+ int iIdx = 0;
+ MemPage pPage = pCur.apPage[pCur.iPage]; /* Btree page of current entry */
+ BtShared pBt = pCur.pBt; /* Btree this cursor belongs to */
+
+ Debug.Assert(pPage != null);
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell);
+ Debug.Assert(cursorHoldsMutex(pCur));
+
+ getCellInfo(pCur);
+ aPayload = pCur.info.pCell; //pCur.info.pCell + pCur.info.nHeader;
+ nKey = (u32)(pPage.intKey != 0 ? 0 : (int)pCur.info.nKey);
+
+ if (NEVER(offset + amt > nKey + pCur.info.nData)
+ || pCur.info.nLocal > pBt.usableSize//&aPayload[pCur.info.nLocal] > &pPage.aData[pBt.usableSize]
+ ) {
+ /* Trying to read or write past the end of the data is an error */
+ return SQLITE_CORRUPT_BKPT();
+ }
+
+ /* Check if data must be read/written to/from the btree page itself. */
+ if (offset < pCur.info.nLocal) {
+ int a = (int)amt;
+ if (a + offset > pCur.info.nLocal) {
+ a = (int)(pCur.info.nLocal - offset);
+ }
+ rc = copyPayload(aPayload, (u32)(offset + pCur.info.iCell + pCur.info.nHeader), pBuf, pBufOffset, (u32)a, eOp, pPage.pDbPage);
+ offset = 0;
+ pBufOffset += (u32)a; //pBuf += a;
+ amt -= (u32)a;
+ } else {
+ offset -= pCur.info.nLocal;
+ }
+
+ if (rc == SQLITE_OK && amt > 0) {
+ u32 ovflSize = (u32)(pBt.usableSize - 4); /* Bytes content per ovfl page */
+ Pgno nextPage;
+
+ nextPage = sqlite3Get4byte(aPayload, pCur.info.nLocal + pCur.info.iCell + pCur.info.nHeader);
#if !SQLITE_OMIT_INCRBLOB
/* If the isIncrblobHandle flag is set and the BtCursor.aOverflow[]
@@ -4492,8 +4120,7 @@ int eOp /* zero to read. non-zero to write. */
}
#endif
- for ( ; rc == SQLITE_OK && amt > 0 && nextPage != 0; iIdx++ )
- {
+ for (; rc == SQLITE_OK && amt > 0 && nextPage != 0; iIdx++) {
#if !SQLITE_OMIT_INCRBLOB
/* If required, populate the overflow page-list cache. */
@@ -4503,89 +4130,81 @@ int eOp /* zero to read. non-zero to write. */
}
#endif
- MemPage MemPageDummy = null;
- if ( offset >= ovflSize )
- {
- /* The only reason to read this page is to obtain the page
- ** number for the next page in the overflow chain. The page
- ** data is not required. So first try to lookup the overflow
- ** page-list cache, if any, then fall back to the getOverflowPage()
- ** function.
- */
+ MemPage MemPageDummy = null;
+ if (offset >= ovflSize) {
+ /* The only reason to read this page is to obtain the page
+ ** number for the next page in the overflow chain. The page
+ ** data is not required. So first try to lookup the overflow
+ ** page-list cache, if any, then fall back to the getOverflowPage()
+ ** function.
+ */
#if !SQLITE_OMIT_INCRBLOB
if( pCur.aOverflow && pCur.aOverflow[iIdx+1] ){
nextPage = pCur.aOverflow[iIdx+1];
} else
#endif
- rc = getOverflowPage( pBt, nextPage, out MemPageDummy, out nextPage );
- offset -= ovflSize;
- }
- else
- {
- /* Need to read this page properly. It contains some of the
- ** range of data that is being read (eOp==null) or written (eOp!=null).
- */
- PgHdr pDbPage = new PgHdr();
- int a = (int)amt;
- rc = sqlite3PagerGet( pBt.pPager, nextPage, ref pDbPage );
- if ( rc == SQLITE_OK )
- {
- aPayload = sqlite3PagerGetData( pDbPage );
- nextPage = sqlite3Get4byte( aPayload );
- if ( a + offset > ovflSize )
- {
- a = (int)( ovflSize - offset );
- }
- rc = copyPayload( aPayload, offset + 4, pBuf, pBufOffset, (u32)a, eOp, pDbPage );
- sqlite3PagerUnref( pDbPage );
- offset = 0;
- amt -= (u32)a;
- pBufOffset += (u32)a;//pBuf += a;
- }
- }
- }
- }
+ rc = getOverflowPage(pBt, nextPage, out MemPageDummy, out nextPage);
+ offset -= ovflSize;
+ } else {
+ /* Need to read this page properly. It contains some of the
+ ** range of data that is being read (eOp==null) or written (eOp!=null).
+ */
+ PgHdr pDbPage = new PgHdr();
+ int a = (int)amt;
+ rc = sqlite3PagerGet(pBt.pPager, nextPage, ref pDbPage);
+ if (rc == SQLITE_OK) {
+ aPayload = sqlite3PagerGetData(pDbPage);
+ nextPage = sqlite3Get4byte(aPayload);
+ if (a + offset > ovflSize) {
+ a = (int)(ovflSize - offset);
+ }
+ rc = copyPayload(aPayload, offset + 4, pBuf, pBufOffset, (u32)a, eOp, pDbPage);
+ sqlite3PagerUnref(pDbPage);
+ offset = 0;
+ amt -= (u32)a;
+ pBufOffset += (u32)a;//pBuf += a;
+ }
+ }
+ }
+ }
- if ( rc == SQLITE_OK && amt > 0 )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- return rc;
-}
+ if (rc == SQLITE_OK && amt > 0) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ return rc;
+ }
-/*
-** Read part of the key associated with cursor pCur. Exactly
-** "amt" bytes will be transfered into pBuf[]. The transfer
-** begins at "offset".
-**
-** The caller must ensure that pCur is pointing to a valid row
-** in the table.
-**
-** Return SQLITE_OK on success or an error code if anything goes
-** wrong. An error is returned if "offset+amt" is larger than
-** the available payload.
-*/
-static int sqlite3BtreeKey( BtCursor pCur, u32 offset, u32 amt, byte[] pBuf )
-{
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- Debug.Assert( pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null );
- Debug.Assert( pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell );
- return accessPayload( pCur, offset, amt, pBuf, 0 );
-}
+ /*
+ ** Read part of the key associated with cursor pCur. Exactly
+ ** "amt" bytes will be transfered into pBuf[]. The transfer
+ ** begins at "offset".
+ **
+ ** The caller must ensure that pCur is pointing to a valid row
+ ** in the table.
+ **
+ ** Return SQLITE_OK on success or an error code if anything goes
+ ** wrong. An error is returned if "offset+amt" is larger than
+ ** the available payload.
+ */
+ static int sqlite3BtreeKey(BtCursor pCur, u32 offset, u32 amt, byte[] pBuf) {
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ Debug.Assert(pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null);
+ Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell);
+ return accessPayload(pCur, offset, amt, pBuf, 0);
+ }
-/*
-** Read part of the data associated with cursor pCur. Exactly
-** "amt" bytes will be transfered into pBuf[]. The transfer
-** begins at "offset".
-**
-** Return SQLITE_OK on success or an error code if anything goes
-** wrong. An error is returned if "offset+amt" is larger than
-** the available payload.
-*/
-static int sqlite3BtreeData( BtCursor pCur, u32 offset, u32 amt, byte[] pBuf )
-{
- int rc;
+ /*
+ ** Read part of the data associated with cursor pCur. Exactly
+ ** "amt" bytes will be transfered into pBuf[]. The transfer
+ ** begins at "offset".
+ **
+ ** Return SQLITE_OK on success or an error code if anything goes
+ ** wrong. An error is returned if "offset+amt" is larger than
+ ** the available payload.
+ */
+ static int sqlite3BtreeData(BtCursor pCur, u32 offset, u32 amt, byte[] pBuf) {
+ int rc;
#if !SQLITE_OMIT_INCRBLOB
if ( pCur.eState==CURSOR_INVALID ){
@@ -4593,2100 +4212,1861 @@ static int sqlite3BtreeData( BtCursor pCur, u32 offset, u32 amt, byte[] pBuf )
}
#endif
- Debug.Assert( cursorHoldsMutex( pCur ) );
- rc = restoreCursorPosition( pCur );
- if ( rc == SQLITE_OK )
- {
- Debug.Assert( pCur.eState == CURSOR_VALID );
- Debug.Assert( pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null );
- Debug.Assert( pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell );
- rc = accessPayload( pCur, offset, amt, pBuf, 0 );
- }
- return rc;
-}
+ Debug.Assert(cursorHoldsMutex(pCur));
+ rc = restoreCursorPosition(pCur);
+ if (rc == SQLITE_OK) {
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ Debug.Assert(pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null);
+ Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell);
+ rc = accessPayload(pCur, offset, amt, pBuf, 0);
+ }
+ return rc;
+ }
-/*
-** Return a pointer to payload information from the entry that the
-** pCur cursor is pointing to. The pointer is to the beginning of
-** the key if skipKey==null and it points to the beginning of data if
-** skipKey==1. The number of bytes of available key/data is written
-** into pAmt. If pAmt==null, then the value returned will not be
-** a valid pointer.
-**
-** This routine is an optimization. It is common for the entire key
-** and data to fit on the local page and for there to be no overflow
-** pages. When that is so, this routine can be used to access the
-** key and data without making a copy. If the key and/or data spills
-** onto overflow pages, then accessPayload() must be used to reassemble
-** the key/data and copy it into a preallocated buffer.
-**
-** The pointer returned by this routine looks directly into the cached
-** page of the database. The data might change or move the next time
-** any btree routine is called.
-*/
-static byte[] fetchPayload(
-BtCursor pCur, /* Cursor pointing to entry to read from */
-ref int pAmt, /* Write the number of available bytes here */
-ref int outOffset, /* Offset into Buffer */
-bool skipKey /* read beginning at data if this is true */
-)
-{
- byte[] aPayload;
- MemPage pPage;
- u32 nKey;
- u32 nLocal;
-
- Debug.Assert( pCur != null && pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- Debug.Assert( cursorHoldsMutex( pCur ) );
- outOffset = -1;
- pPage = pCur.apPage[pCur.iPage];
- Debug.Assert( pCur.aiIdx[pCur.iPage] < pPage.nCell );
- if ( NEVER( pCur.info.nSize == 0 ) )
- {
- btreeParseCell( pCur.apPage[pCur.iPage], pCur.aiIdx[pCur.iPage],
- ref pCur.info );
- }
- //aPayload = pCur.info.pCell;
- //aPayload += pCur.info.nHeader;
- aPayload = sqlite3Malloc( pCur.info.nSize - pCur.info.nHeader );
- if ( pPage.intKey != 0 )
- {
- nKey = 0;
- }
- else
- {
- nKey = (u32)pCur.info.nKey;
- }
- if ( skipKey )
- {
- //aPayload += nKey;
- outOffset = (int)( pCur.info.iCell + pCur.info.nHeader + nKey );
- Buffer.BlockCopy( pCur.info.pCell, outOffset, aPayload, 0, (int)( pCur.info.nSize - pCur.info.nHeader - nKey ) );
- nLocal = pCur.info.nLocal - nKey;
- }
- else
- {
- outOffset = (int)( pCur.info.iCell + pCur.info.nHeader );
- Buffer.BlockCopy( pCur.info.pCell, outOffset, aPayload, 0, pCur.info.nSize - pCur.info.nHeader );
- nLocal = pCur.info.nLocal;
- Debug.Assert( nLocal <= nKey );
- }
- pAmt = (int)nLocal;
- return aPayload;
-}
+ /*
+ ** Return a pointer to payload information from the entry that the
+ ** pCur cursor is pointing to. The pointer is to the beginning of
+ ** the key if skipKey==null and it points to the beginning of data if
+ ** skipKey==1. The number of bytes of available key/data is written
+ ** into pAmt. If pAmt==null, then the value returned will not be
+ ** a valid pointer.
+ **
+ ** This routine is an optimization. It is common for the entire key
+ ** and data to fit on the local page and for there to be no overflow
+ ** pages. When that is so, this routine can be used to access the
+ ** key and data without making a copy. If the key and/or data spills
+ ** onto overflow pages, then accessPayload() must be used to reassemble
+ ** the key/data and copy it into a preallocated buffer.
+ **
+ ** The pointer returned by this routine looks directly into the cached
+ ** page of the database. The data might change or move the next time
+ ** any btree routine is called.
+ */
+ static byte[] fetchPayload(
+ BtCursor pCur, /* Cursor pointing to entry to read from */
+ ref int pAmt, /* Write the number of available bytes here */
+ ref int outOffset, /* Offset into Buffer */
+ bool skipKey /* read beginning at data if this is true */
+ ) {
+ byte[] aPayload;
+ MemPage pPage;
+ u32 nKey;
+ u32 nLocal;
+
+ Debug.Assert(pCur != null && pCur.iPage >= 0 && pCur.apPage[pCur.iPage] != null);
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ Debug.Assert(cursorHoldsMutex(pCur));
+ outOffset = -1;
+ pPage = pCur.apPage[pCur.iPage];
+ Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell);
+ if (NEVER(pCur.info.nSize == 0)) {
+ btreeParseCell(pCur.apPage[pCur.iPage], pCur.aiIdx[pCur.iPage],
+ ref pCur.info);
+ }
+ //aPayload = pCur.info.pCell;
+ //aPayload += pCur.info.nHeader;
+ aPayload = sqlite3Malloc(pCur.info.nSize - pCur.info.nHeader);
+ if (pPage.intKey != 0) {
+ nKey = 0;
+ } else {
+ nKey = (u32)pCur.info.nKey;
+ }
+ if (skipKey) {
+ //aPayload += nKey;
+ outOffset = (int)(pCur.info.iCell + pCur.info.nHeader + nKey);
+ Buffer.BlockCopy(pCur.info.pCell, outOffset, aPayload, 0, (int)(pCur.info.nSize - pCur.info.nHeader - nKey));
+ nLocal = pCur.info.nLocal - nKey;
+ } else {
+ outOffset = (int)(pCur.info.iCell + pCur.info.nHeader);
+ Buffer.BlockCopy(pCur.info.pCell, outOffset, aPayload, 0, pCur.info.nSize - pCur.info.nHeader);
+ nLocal = pCur.info.nLocal;
+ Debug.Assert(nLocal <= nKey);
+ }
+ pAmt = (int)nLocal;
+ return aPayload;
+ }
-/*
-** For the entry that cursor pCur is point to, return as
-** many bytes of the key or data as are available on the local
-** b-tree page. Write the number of available bytes into pAmt.
-**
-** The pointer returned is ephemeral. The key/data may move
-** or be destroyed on the next call to any Btree routine,
-** including calls from other threads against the same cache.
-** Hence, a mutex on the BtShared should be held prior to calling
-** this routine.
-**
-** These routines is used to get quick access to key and data
-** in the common case where no overflow pages are used.
-*/
-static byte[] sqlite3BtreeKeyFetch( BtCursor pCur, ref int pAmt, ref int outOffset )
-{
- byte[] p = null;
- Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) );
- Debug.Assert( cursorHoldsMutex( pCur ) );
- if ( ALWAYS( pCur.eState == CURSOR_VALID ) )
- {
- p = fetchPayload( pCur, ref pAmt, ref outOffset, false );
- }
- return p;
-}
-static byte[] sqlite3BtreeDataFetch( BtCursor pCur, ref int pAmt, ref int outOffset )
-{
- byte[] p = null;
- Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) );
- Debug.Assert( cursorHoldsMutex( pCur ) );
- if ( ALWAYS( pCur.eState == CURSOR_VALID ) )
- {
- p = fetchPayload( pCur, ref pAmt, ref outOffset, true );
- }
- return p;
-}
+ /*
+ ** For the entry that cursor pCur is point to, return as
+ ** many bytes of the key or data as are available on the local
+ ** b-tree page. Write the number of available bytes into pAmt.
+ **
+ ** The pointer returned is ephemeral. The key/data may move
+ ** or be destroyed on the next call to any Btree routine,
+ ** including calls from other threads against the same cache.
+ ** Hence, a mutex on the BtShared should be held prior to calling
+ ** this routine.
+ **
+ ** These routines is used to get quick access to key and data
+ ** in the common case where no overflow pages are used.
+ */
+ static byte[] sqlite3BtreeKeyFetch(BtCursor pCur, ref int pAmt, ref int outOffset) {
+ byte[] p = null;
+ Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex));
+ Debug.Assert(cursorHoldsMutex(pCur));
+ if (ALWAYS(pCur.eState == CURSOR_VALID)) {
+ p = fetchPayload(pCur, ref pAmt, ref outOffset, false);
+ }
+ return p;
+ }
+ static byte[] sqlite3BtreeDataFetch(BtCursor pCur, ref int pAmt, ref int outOffset) {
+ byte[] p = null;
+ Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex));
+ Debug.Assert(cursorHoldsMutex(pCur));
+ if (ALWAYS(pCur.eState == CURSOR_VALID)) {
+ p = fetchPayload(pCur, ref pAmt, ref outOffset, true);
+ }
+ return p;
+ }
-/*
-** Move the cursor down to a new child page. The newPgno argument is the
-** page number of the child page to move to.
-**
-** This function returns SQLITE_CORRUPT if the page-header flags field of
-** the new child page does not match the flags field of the parent (i.e.
-** if an intkey page appears to be the parent of a non-intkey page, or
-** vice-versa).
-*/
-static int moveToChild( BtCursor pCur, u32 newPgno )
-{
- int rc;
- int i = pCur.iPage;
- MemPage pNewPage = new MemPage();
- BtShared pBt = pCur.pBt;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- Debug.Assert( pCur.iPage < BTCURSOR_MAX_DEPTH );
- if ( pCur.iPage >= ( BTCURSOR_MAX_DEPTH - 1 ) )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- rc = getAndInitPage( pBt, newPgno, ref pNewPage );
- if ( rc != 0 )
- return rc;
- pCur.apPage[i + 1] = pNewPage;
- pCur.aiIdx[i + 1] = 0;
- pCur.iPage++;
-
- pCur.info.nSize = 0;
- pCur.validNKey = false;
- if ( pNewPage.nCell < 1 || pNewPage.intKey != pCur.apPage[i].intKey )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- return SQLITE_OK;
-}
+ /*
+ ** Move the cursor down to a new child page. The newPgno argument is the
+ ** page number of the child page to move to.
+ **
+ ** This function returns SQLITE_CORRUPT if the page-header flags field of
+ ** the new child page does not match the flags field of the parent (i.e.
+ ** if an intkey page appears to be the parent of a non-intkey page, or
+ ** vice-versa).
+ */
+ static int moveToChild(BtCursor pCur, u32 newPgno) {
+ int rc;
+ int i = pCur.iPage;
+ MemPage pNewPage = new MemPage();
+ BtShared pBt = pCur.pBt;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ Debug.Assert(pCur.iPage < BTCURSOR_MAX_DEPTH);
+ if (pCur.iPage >= (BTCURSOR_MAX_DEPTH - 1)) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ rc = getAndInitPage(pBt, newPgno, ref pNewPage);
+ if (rc != 0)
+ return rc;
+ pCur.apPage[i + 1] = pNewPage;
+ pCur.aiIdx[i + 1] = 0;
+ pCur.iPage++;
+
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+ if (pNewPage.nCell < 1 || pNewPage.intKey != pCur.apPage[i].intKey) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ return SQLITE_OK;
+ }
#if !NDEBUG
-/*
-** Page pParent is an internal (non-leaf) tree page. This function
-** asserts that page number iChild is the left-child if the iIdx'th
-** cell in page pParent. Or, if iIdx is equal to the total number of
-** cells in pParent, that page number iChild is the right-child of
-** the page.
-*/
-static void assertParentIndex( MemPage pParent, int iIdx, Pgno iChild )
-{
- Debug.Assert( iIdx <= pParent.nCell );
- if ( iIdx == pParent.nCell )
- {
- Debug.Assert( sqlite3Get4byte( pParent.aData, pParent.hdrOffset + 8 ) == iChild );
- }
- else
- {
- Debug.Assert( sqlite3Get4byte( pParent.aData, findCell( pParent, iIdx ) ) == iChild );
- }
-}
+ /*
+ ** Page pParent is an internal (non-leaf) tree page. This function
+ ** asserts that page number iChild is the left-child if the iIdx'th
+ ** cell in page pParent. Or, if iIdx is equal to the total number of
+ ** cells in pParent, that page number iChild is the right-child of
+ ** the page.
+ */
+ static void assertParentIndex(MemPage pParent, int iIdx, Pgno iChild) {
+ Debug.Assert(iIdx <= pParent.nCell);
+ if (iIdx == pParent.nCell) {
+ Debug.Assert(sqlite3Get4byte(pParent.aData, pParent.hdrOffset + 8) == iChild);
+ } else {
+ Debug.Assert(sqlite3Get4byte(pParent.aData, findCell(pParent, iIdx)) == iChild);
+ }
+ }
#else
//# define assertParentIndex(x,y,z)
static void assertParentIndex(MemPage pParent, int iIdx, Pgno iChild) { }
#endif
-/*
-** Move the cursor up to the parent page.
-**
-** pCur.idx is set to the cell index that contains the pointer
-** to the page we are coming from. If we are coming from the
-** right-most child page then pCur.idx is set to one more than
-** the largest cell index.
-*/
-static void moveToParent( BtCursor pCur )
-{
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- Debug.Assert( pCur.iPage > 0 );
- Debug.Assert( pCur.apPage[pCur.iPage] != null );
- assertParentIndex(
- pCur.apPage[pCur.iPage - 1],
- pCur.aiIdx[pCur.iPage - 1],
- pCur.apPage[pCur.iPage].pgno
- );
- releasePage( pCur.apPage[pCur.iPage] );
- pCur.iPage--;
- pCur.info.nSize = 0;
- pCur.validNKey = false;
-}
+ /*
+ ** Move the cursor up to the parent page.
+ **
+ ** pCur.idx is set to the cell index that contains the pointer
+ ** to the page we are coming from. If we are coming from the
+ ** right-most child page then pCur.idx is set to one more than
+ ** the largest cell index.
+ */
+ static void moveToParent(BtCursor pCur) {
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ Debug.Assert(pCur.iPage > 0);
+ Debug.Assert(pCur.apPage[pCur.iPage] != null);
+ assertParentIndex(
+ pCur.apPage[pCur.iPage - 1],
+ pCur.aiIdx[pCur.iPage - 1],
+ pCur.apPage[pCur.iPage].pgno
+ );
+ releasePage(pCur.apPage[pCur.iPage]);
+ pCur.iPage--;
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+ }
-/*
-** Move the cursor to point to the root page of its b-tree structure.
-**
-** If the table has a virtual root page, then the cursor is moved to point
-** to the virtual root page instead of the actual root page. A table has a
-** virtual root page when the actual root page contains no cells and a
-** single child page. This can only happen with the table rooted at page 1.
-**
-** If the b-tree structure is empty, the cursor state is set to
-** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
-** cell located on the root (or virtual root) page and the cursor state
-** is set to CURSOR_VALID.
-**
-** If this function returns successfully, it may be assumed that the
-** page-header flags indicate that the [virtual] root-page is the expected
-** kind of b-tree page (i.e. if when opening the cursor the caller did not
-** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
-** indicating a table b-tree, or if the caller did specify a KeyInfo
-** structure the flags byte is set to 0x02 or 0x0A, indicating an index
-** b-tree).
-*/
-static int moveToRoot( BtCursor pCur )
-{
- MemPage pRoot;
- int rc = SQLITE_OK;
- Btree p = pCur.pBtree;
- BtShared pBt = p.pBt;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
- Debug.Assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
- Debug.Assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
- if ( pCur.eState >= CURSOR_REQUIRESEEK )
- {
- if ( pCur.eState == CURSOR_FAULT )
- {
- Debug.Assert( pCur.skipNext != SQLITE_OK );
- return pCur.skipNext;
- }
- sqlite3BtreeClearCursor( pCur );
- }
+ /*
+ ** Move the cursor to point to the root page of its b-tree structure.
+ **
+ ** If the table has a virtual root page, then the cursor is moved to point
+ ** to the virtual root page instead of the actual root page. A table has a
+ ** virtual root page when the actual root page contains no cells and a
+ ** single child page. This can only happen with the table rooted at page 1.
+ **
+ ** If the b-tree structure is empty, the cursor state is set to
+ ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
+ ** cell located on the root (or virtual root) page and the cursor state
+ ** is set to CURSOR_VALID.
+ **
+ ** If this function returns successfully, it may be assumed that the
+ ** page-header flags indicate that the [virtual] root-page is the expected
+ ** kind of b-tree page (i.e. if when opening the cursor the caller did not
+ ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
+ ** indicating a table b-tree, or if the caller did specify a KeyInfo
+ ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
+ ** b-tree).
+ */
+ static int moveToRoot(BtCursor pCur) {
+ MemPage pRoot;
+ int rc = SQLITE_OK;
+ Btree p = pCur.pBtree;
+ BtShared pBt = p.pBt;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(CURSOR_INVALID < CURSOR_REQUIRESEEK);
+ Debug.Assert(CURSOR_VALID < CURSOR_REQUIRESEEK);
+ Debug.Assert(CURSOR_FAULT > CURSOR_REQUIRESEEK);
+ if (pCur.eState >= CURSOR_REQUIRESEEK) {
+ if (pCur.eState == CURSOR_FAULT) {
+ Debug.Assert(pCur.skipNext != SQLITE_OK);
+ return pCur.skipNext;
+ }
+ sqlite3BtreeClearCursor(pCur);
+ }
- if ( pCur.iPage >= 0 )
- {
- int i;
- for ( i = 1; i <= pCur.iPage; i++ )
- {
- releasePage( pCur.apPage[i] );
- }
- pCur.iPage = 0;
- }
- else
- {
- rc = getAndInitPage( pBt, pCur.pgnoRoot, ref pCur.apPage[0] );
- if ( rc != SQLITE_OK )
- {
- pCur.eState = CURSOR_INVALID;
- return rc;
- }
- pCur.iPage = 0;
-
- /* If pCur.pKeyInfo is not NULL, then the caller that opened this cursor
- ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
- ** NULL, the caller expects a table b-tree. If this is not the case,
- ** return an SQLITE_CORRUPT error. */
- Debug.Assert( pCur.apPage[0].intKey == 1 || pCur.apPage[0].intKey == 0 );
- if ( ( pCur.pKeyInfo == null ) != ( pCur.apPage[0].intKey != 0 ) )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- }
-
- /* Assert that the root page is of the correct type. This must be the
- ** case as the call to this function that loaded the root-page (either
- ** this call or a previous invocation) would have detected corruption
- ** if the assumption were not true, and it is not possible for the flags
- ** byte to have been modified while this cursor is holding a reference
- ** to the page. */
- pRoot = pCur.apPage[0];
- Debug.Assert( pRoot.pgno == pCur.pgnoRoot );
- Debug.Assert( pRoot.isInit != 0 && ( pCur.pKeyInfo == null ) == ( pRoot.intKey != 0 ) );
-
- pCur.aiIdx[0] = 0;
- pCur.info.nSize = 0;
- pCur.atLast = 0;
- pCur.validNKey = false;
-
- if ( pRoot.nCell == 0 && 0 == pRoot.leaf )
- {
- Pgno subpage;
- if ( pRoot.pgno != 1 )
- return SQLITE_CORRUPT_BKPT();
- subpage = sqlite3Get4byte( pRoot.aData, pRoot.hdrOffset + 8 );
- pCur.eState = CURSOR_VALID;
- rc = moveToChild( pCur, subpage );
- }
- else
- {
- pCur.eState = ( ( pRoot.nCell > 0 ) ? CURSOR_VALID : CURSOR_INVALID );
- }
- return rc;
-}
+ if (pCur.iPage >= 0) {
+ int i;
+ for (i = 1; i <= pCur.iPage; i++) {
+ releasePage(pCur.apPage[i]);
+ }
+ pCur.iPage = 0;
+ } else {
+ rc = getAndInitPage(pBt, pCur.pgnoRoot, ref pCur.apPage[0]);
+ if (rc != SQLITE_OK) {
+ pCur.eState = CURSOR_INVALID;
+ return rc;
+ }
+ pCur.iPage = 0;
+
+ /* If pCur.pKeyInfo is not NULL, then the caller that opened this cursor
+ ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
+ ** NULL, the caller expects a table b-tree. If this is not the case,
+ ** return an SQLITE_CORRUPT error. */
+ Debug.Assert(pCur.apPage[0].intKey == 1 || pCur.apPage[0].intKey == 0);
+ if ((pCur.pKeyInfo == null) != (pCur.apPage[0].intKey != 0)) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ }
-/*
-** Move the cursor down to the left-most leaf entry beneath the
-** entry to which it is currently pointing.
-**
-** The left-most leaf is the one with the smallest key - the first
-** in ascending order.
-*/
-static int moveToLeftmost( BtCursor pCur )
-{
- Pgno pgno;
- int rc = SQLITE_OK;
- MemPage pPage;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- while ( rc == SQLITE_OK && 0 == ( pPage = pCur.apPage[pCur.iPage] ).leaf )
- {
- Debug.Assert( pCur.aiIdx[pCur.iPage] < pPage.nCell );
- pgno = sqlite3Get4byte( pPage.aData, findCell( pPage, pCur.aiIdx[pCur.iPage] ) );
- rc = moveToChild( pCur, pgno );
- }
- return rc;
-}
+ /* Assert that the root page is of the correct type. This must be the
+ ** case as the call to this function that loaded the root-page (either
+ ** this call or a previous invocation) would have detected corruption
+ ** if the assumption were not true, and it is not possible for the flags
+ ** byte to have been modified while this cursor is holding a reference
+ ** to the page. */
+ pRoot = pCur.apPage[0];
+ Debug.Assert(pRoot.pgno == pCur.pgnoRoot);
+ Debug.Assert(pRoot.isInit != 0 && (pCur.pKeyInfo == null) == (pRoot.intKey != 0));
+
+ pCur.aiIdx[0] = 0;
+ pCur.info.nSize = 0;
+ pCur.atLast = 0;
+ pCur.validNKey = false;
+
+ if (pRoot.nCell == 0 && 0 == pRoot.leaf) {
+ Pgno subpage;
+ if (pRoot.pgno != 1)
+ return SQLITE_CORRUPT_BKPT();
+ subpage = sqlite3Get4byte(pRoot.aData, pRoot.hdrOffset + 8);
+ pCur.eState = CURSOR_VALID;
+ rc = moveToChild(pCur, subpage);
+ } else {
+ pCur.eState = ((pRoot.nCell > 0) ? CURSOR_VALID : CURSOR_INVALID);
+ }
+ return rc;
+ }
-/*
-** Move the cursor down to the right-most leaf entry beneath the
-** page to which it is currently pointing. Notice the difference
-** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
-** finds the left-most entry beneath the *entry* whereas moveToRightmost()
-** finds the right-most entry beneath the page*.
-**
-** The right-most entry is the one with the largest key - the last
-** key in ascending order.
-*/
-static int moveToRightmost( BtCursor pCur )
-{
- Pgno pgno;
- int rc = SQLITE_OK;
- MemPage pPage = null;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.eState == CURSOR_VALID );
- while ( rc == SQLITE_OK && 0 == ( pPage = pCur.apPage[pCur.iPage] ).leaf )
- {
- pgno = sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 );
- pCur.aiIdx[pCur.iPage] = pPage.nCell;
- rc = moveToChild( pCur, pgno );
- }
- if ( rc == SQLITE_OK )
- {
- pCur.aiIdx[pCur.iPage] = (u16)( pPage.nCell - 1 );
- pCur.info.nSize = 0;
- pCur.validNKey = false;
- }
- return rc;
-}
+ /*
+ ** Move the cursor down to the left-most leaf entry beneath the
+ ** entry to which it is currently pointing.
+ **
+ ** The left-most leaf is the one with the smallest key - the first
+ ** in ascending order.
+ */
+ static int moveToLeftmost(BtCursor pCur) {
+ Pgno pgno;
+ int rc = SQLITE_OK;
+ MemPage pPage;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ while (rc == SQLITE_OK && 0 == (pPage = pCur.apPage[pCur.iPage]).leaf) {
+ Debug.Assert(pCur.aiIdx[pCur.iPage] < pPage.nCell);
+ pgno = sqlite3Get4byte(pPage.aData, findCell(pPage, pCur.aiIdx[pCur.iPage]));
+ rc = moveToChild(pCur, pgno);
+ }
+ return rc;
+ }
-/* Move the cursor to the first entry in the table. Return SQLITE_OK
-** on success. Set pRes to 0 if the cursor actually points to something
-** or set pRes to 1 if the table is empty.
-*/
-static int sqlite3BtreeFirst( BtCursor pCur, ref int pRes )
-{
- int rc;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) );
- rc = moveToRoot( pCur );
- if ( rc == SQLITE_OK )
- {
- if ( pCur.eState == CURSOR_INVALID )
- {
- Debug.Assert( pCur.apPage[pCur.iPage].nCell == 0 );
- pRes = 1;
- }
- else
- {
- Debug.Assert( pCur.apPage[pCur.iPage].nCell > 0 );
- pRes = 0;
- rc = moveToLeftmost( pCur );
- }
- }
- return rc;
-}
+ /*
+ ** Move the cursor down to the right-most leaf entry beneath the
+ ** page to which it is currently pointing. Notice the difference
+ ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
+ ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
+ ** finds the right-most entry beneath the page*.
+ **
+ ** The right-most entry is the one with the largest key - the last
+ ** key in ascending order.
+ */
+ static int moveToRightmost(BtCursor pCur) {
+ Pgno pgno;
+ int rc = SQLITE_OK;
+ MemPage pPage = null;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ while (rc == SQLITE_OK && 0 == (pPage = pCur.apPage[pCur.iPage]).leaf) {
+ pgno = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8);
+ pCur.aiIdx[pCur.iPage] = pPage.nCell;
+ rc = moveToChild(pCur, pgno);
+ }
+ if (rc == SQLITE_OK) {
+ pCur.aiIdx[pCur.iPage] = (u16)(pPage.nCell - 1);
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+ }
+ return rc;
+ }
-/* Move the cursor to the last entry in the table. Return SQLITE_OK
-** on success. Set pRes to 0 if the cursor actually points to something
-** or set pRes to 1 if the table is empty.
-*/
-static int sqlite3BtreeLast( BtCursor pCur, ref int pRes )
-{
- int rc;
+ /* Move the cursor to the first entry in the table. Return SQLITE_OK
+ ** on success. Set pRes to 0 if the cursor actually points to something
+ ** or set pRes to 1 if the table is empty.
+ */
+ static int sqlite3BtreeFirst(BtCursor pCur, ref int pRes) {
+ int rc;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex));
+ rc = moveToRoot(pCur);
+ if (rc == SQLITE_OK) {
+ if (pCur.eState == CURSOR_INVALID) {
+ Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0);
+ pRes = 1;
+ } else {
+ Debug.Assert(pCur.apPage[pCur.iPage].nCell > 0);
+ pRes = 0;
+ rc = moveToLeftmost(pCur);
+ }
+ }
+ return rc;
+ }
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) );
+ /* Move the cursor to the last entry in the table. Return SQLITE_OK
+ ** on success. Set pRes to 0 if the cursor actually points to something
+ ** or set pRes to 1 if the table is empty.
+ */
+ static int sqlite3BtreeLast(BtCursor pCur, ref int pRes) {
+ int rc;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex));
- /* If the cursor already points to the last entry, this is a no-op. */
- if ( CURSOR_VALID == pCur.eState && pCur.atLast != 0 )
- {
+ /* If the cursor already points to the last entry, this is a no-op. */
+ if (CURSOR_VALID == pCur.eState && pCur.atLast != 0) {
#if SQLITE_DEBUG
- /* This block serves to Debug.Assert() that the cursor really does point
-** to the last entry in the b-tree. */
- int ii;
- for ( ii = 0; ii < pCur.iPage; ii++ )
- {
- Debug.Assert( pCur.aiIdx[ii] == pCur.apPage[ii].nCell );
- }
- Debug.Assert( pCur.aiIdx[pCur.iPage] == pCur.apPage[pCur.iPage].nCell - 1 );
- Debug.Assert( pCur.apPage[pCur.iPage].leaf != 0 );
+ /* This block serves to Debug.Assert() that the cursor really does point
+ ** to the last entry in the b-tree. */
+ int ii;
+ for (ii = 0; ii < pCur.iPage; ii++) {
+ Debug.Assert(pCur.aiIdx[ii] == pCur.apPage[ii].nCell);
+ }
+ Debug.Assert(pCur.aiIdx[pCur.iPage] == pCur.apPage[pCur.iPage].nCell - 1);
+ Debug.Assert(pCur.apPage[pCur.iPage].leaf != 0);
#endif
- return SQLITE_OK;
- }
+ return SQLITE_OK;
+ }
- rc = moveToRoot( pCur );
- if ( rc == SQLITE_OK )
- {
- if ( CURSOR_INVALID == pCur.eState )
- {
- Debug.Assert( pCur.apPage[pCur.iPage].nCell == 0 );
- pRes = 1;
- }
- else
- {
- Debug.Assert( pCur.eState == CURSOR_VALID );
- pRes = 0;
- rc = moveToRightmost( pCur );
- pCur.atLast = (u8)( rc == SQLITE_OK ? 1 : 0 );
- }
- }
- return rc;
-}
+ rc = moveToRoot(pCur);
+ if (rc == SQLITE_OK) {
+ if (CURSOR_INVALID == pCur.eState) {
+ Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0);
+ pRes = 1;
+ } else {
+ Debug.Assert(pCur.eState == CURSOR_VALID);
+ pRes = 0;
+ rc = moveToRightmost(pCur);
+ pCur.atLast = (u8)(rc == SQLITE_OK ? 1 : 0);
+ }
+ }
+ return rc;
+ }
-/* Move the cursor so that it points to an entry near the key
-** specified by pIdxKey or intKey. Return a success code.
-**
-** For INTKEY tables, the intKey parameter is used. pIdxKey
-** must be NULL. For index tables, pIdxKey is used and intKey
-** is ignored.
-**
-** If an exact match is not found, then the cursor is always
-** left pointing at a leaf page which would hold the entry if it
-** were present. The cursor might point to an entry that comes
-** before or after the key.
-**
-** An integer is written into pRes which is the result of
-** comparing the key with the entry to which the cursor is
-** pointing. The meaning of the integer written into
-** pRes is as follows:
-**
-** pRes<0 The cursor is left pointing at an entry that
-** is smaller than intKey/pIdxKey or if the table is empty
-** and the cursor is therefore left point to nothing.
-**
-** pRes==null The cursor is left pointing at an entry that
-** exactly matches intKey/pIdxKey.
-**
-** pRes>0 The cursor is left pointing at an entry that
-** is larger than intKey/pIdxKey.
-**
-*/
-static int sqlite3BtreeMovetoUnpacked(
-BtCursor pCur, /* The cursor to be moved */
-UnpackedRecord pIdxKey, /* Unpacked index key */
-i64 intKey, /* The table key */
-int biasRight, /* If true, bias the search to the high end */
-ref int pRes /* Write search results here */
-)
-{
- int rc;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( sqlite3_mutex_held( pCur.pBtree.db.mutex ) );
- // Not needed in C# // Debug.Assert( pRes != 0 );
- Debug.Assert( ( pIdxKey == null ) == ( pCur.pKeyInfo == null ) );
-
- /* If the cursor is already positioned at the point we are trying
- ** to move to, then just return without doing any work */
- if ( pCur.eState == CURSOR_VALID && pCur.validNKey
- && pCur.apPage[0].intKey != 0
- )
- {
- if ( pCur.info.nKey == intKey )
- {
- pRes = 0;
- return SQLITE_OK;
- }
- if ( pCur.atLast != 0 && pCur.info.nKey < intKey )
- {
- pRes = -1;
- return SQLITE_OK;
- }
- }
-
- rc = moveToRoot( pCur );
- if ( rc != 0 )
- {
- return rc;
- }
- Debug.Assert( pCur.apPage[pCur.iPage] != null );
- Debug.Assert( pCur.apPage[pCur.iPage].isInit != 0 );
- Debug.Assert( pCur.apPage[pCur.iPage].nCell > 0 || pCur.eState == CURSOR_INVALID );
- if ( pCur.eState == CURSOR_INVALID )
- {
- pRes = -1;
- Debug.Assert( pCur.apPage[pCur.iPage].nCell == 0 );
- return SQLITE_OK;
- }
- Debug.Assert( pCur.apPage[0].intKey != 0 || pIdxKey != null );
- for ( ; ; )
- {
- int lwr, upr, idx;
- Pgno chldPg;
- MemPage pPage = pCur.apPage[pCur.iPage];
- int c;
-
- /* pPage.nCell must be greater than zero. If this is the root-page
- ** the cursor would have been INVALID above and this for(;;) loop
- ** not run. If this is not the root-page, then the moveToChild() routine
- ** would have already detected db corruption. Similarly, pPage must
- ** be the right kind (index or table) of b-tree page. Otherwise
- ** a moveToChild() or moveToRoot() call would have detected corruption. */
- Debug.Assert( pPage.nCell > 0 );
- Debug.Assert( pPage.intKey == ( ( pIdxKey == null ) ? 1 : 0 ) );
- lwr = 0;
- upr = pPage.nCell - 1;
- if ( biasRight != 0 )
- {
- pCur.aiIdx[pCur.iPage] = (u16)( idx = upr );
- }
- else
- {
- pCur.aiIdx[pCur.iPage] = (u16)( idx = ( upr + lwr ) / 2 );
- }
- for ( ; ; )
- {
- int pCell; /* Pointer to current cell in pPage */
-
- Debug.Assert( idx == pCur.aiIdx[pCur.iPage] );
- pCur.info.nSize = 0;
- pCell = findCell( pPage, idx ) + pPage.childPtrSize;
- if ( pPage.intKey != 0 )
- {
- i64 nCellKey = 0;
- if ( pPage.hasData != 0 )
- {
- u32 Dummy0 = 0;
- pCell += getVarint32( pPage.aData, pCell, out Dummy0 );
- }
- getVarint( pPage.aData, pCell, out nCellKey );
- if ( nCellKey == intKey )
- {
- c = 0;
- }
- else if ( nCellKey < intKey )
- {
- c = -1;
- }
- else
- {
- Debug.Assert( nCellKey > intKey );
- c = +1;
- }
- pCur.validNKey = true;
- pCur.info.nKey = nCellKey;
- }
- else
- {
- /* The maximum supported page-size is 65536 bytes. This means that
- ** the maximum number of record bytes stored on an index B-Tree
- ** page is less than 16384 bytes and may be stored as a 2-byte
- ** varint. This information is used to attempt to avoid parsing
- ** the entire cell by checking for the cases where the record is
- ** stored entirely within the b-tree page by inspecting the first
- ** 2 bytes of the cell.
- */
- int nCell = pPage.aData[pCell + 0]; //pCell[0];
- if ( 0 == ( nCell & 0x80 ) && nCell <= pPage.maxLocal )
- {
- /* This branch runs if the record-size field of the cell is a
- ** single byte varint and the record fits entirely on the main
- ** b-tree page. */
- c = sqlite3VdbeRecordCompare( nCell, pPage.aData, pCell + 1, pIdxKey ); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[1], pIdxKey );
- }
- else if ( 0 == ( pPage.aData[pCell + 1] & 0x80 )//!(pCell[1] & 0x80)
- && ( nCell = ( ( nCell & 0x7f ) << 7 ) + pPage.aData[pCell + 1] ) <= pPage.maxLocal//pCell[1])<=pPage.maxLocal
- )
- {
- /* The record-size field is a 2 byte varint and the record
- ** fits entirely on the main b-tree page. */
- c = sqlite3VdbeRecordCompare( nCell, pPage.aData, pCell + 2, pIdxKey ); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[2], pIdxKey );
- }
- else
- {
- /* The record flows over onto one or more overflow pages. In
- ** this case the whole cell needs to be parsed, a buffer allocated
- ** and accessPayload() used to retrieve the record into the
- ** buffer before VdbeRecordCompare() can be called. */
- u8[] pCellKey;
- u8[] pCellBody = new u8[pPage.aData.Length - pCell + pPage.childPtrSize];
- Buffer.BlockCopy( pPage.aData, pCell - pPage.childPtrSize, pCellBody, 0, pCellBody.Length );// u8 * const pCellBody = pCell - pPage->childPtrSize;
- btreeParseCellPtr( pPage, pCellBody, ref pCur.info );
- nCell = (int)pCur.info.nKey;
- pCellKey = sqlite3Malloc( nCell );
- //if ( pCellKey == null )
- //{
- // rc = SQLITE_NOMEM;
- // goto moveto_finish;
- //}
- rc = accessPayload( pCur, 0, (u32)nCell, pCellKey, 0 );
- if ( rc != 0 )
- {
- pCellKey = null;// sqlite3_free(ref pCellKey );
- goto moveto_finish;
- }
- c = sqlite3VdbeRecordCompare( nCell, pCellKey, pIdxKey );
- pCellKey = null;// sqlite3_free(ref pCellKey );
- }
- }
- if ( c == 0 )
- {
- if ( pPage.intKey != 0 && 0 == pPage.leaf )
- {
- lwr = idx;
- upr = lwr - 1;
- break;
- }
- else
- {
- pRes = 0;
- rc = SQLITE_OK;
- goto moveto_finish;
- }
- }
- if ( c < 0 )
- {
- lwr = idx + 1;
- }
- else
- {
- upr = idx - 1;
- }
- if ( lwr > upr )
- {
- break;
- }
- pCur.aiIdx[pCur.iPage] = (u16)( idx = ( lwr + upr ) / 2 );
- }
- Debug.Assert( lwr == upr + 1 );
- Debug.Assert( pPage.isInit != 0 );
- if ( pPage.leaf != 0 )
- {
- chldPg = 0;
- }
- else if ( lwr >= pPage.nCell )
- {
- chldPg = sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 );
- }
- else
- {
- chldPg = sqlite3Get4byte( pPage.aData, findCell( pPage, lwr ) );
- }
- if ( chldPg == 0 )
- {
- Debug.Assert( pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell );
- pRes = c;
- rc = SQLITE_OK;
- goto moveto_finish;
- }
- pCur.aiIdx[pCur.iPage] = (u16)lwr;
- pCur.info.nSize = 0;
- pCur.validNKey = false;
- rc = moveToChild( pCur, chldPg );
- if ( rc != 0 )
- goto moveto_finish;
- }
-moveto_finish:
- return rc;
-}
+ /* Move the cursor so that it points to an entry near the key
+ ** specified by pIdxKey or intKey. Return a success code.
+ **
+ ** For INTKEY tables, the intKey parameter is used. pIdxKey
+ ** must be NULL. For index tables, pIdxKey is used and intKey
+ ** is ignored.
+ **
+ ** If an exact match is not found, then the cursor is always
+ ** left pointing at a leaf page which would hold the entry if it
+ ** were present. The cursor might point to an entry that comes
+ ** before or after the key.
+ **
+ ** An integer is written into pRes which is the result of
+ ** comparing the key with the entry to which the cursor is
+ ** pointing. The meaning of the integer written into
+ ** pRes is as follows:
+ **
+ ** pRes<0 The cursor is left pointing at an entry that
+ ** is smaller than intKey/pIdxKey or if the table is empty
+ ** and the cursor is therefore left point to nothing.
+ **
+ ** pRes==null The cursor is left pointing at an entry that
+ ** exactly matches intKey/pIdxKey.
+ **
+ ** pRes>0 The cursor is left pointing at an entry that
+ ** is larger than intKey/pIdxKey.
+ **
+ */
+ static int sqlite3BtreeMovetoUnpacked(
+ BtCursor pCur, /* The cursor to be moved */
+ UnpackedRecord pIdxKey, /* Unpacked index key */
+ i64 intKey, /* The table key */
+ int biasRight, /* If true, bias the search to the high end */
+ ref int pRes /* Write search results here */
+ ) {
+ int rc;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(sqlite3_mutex_held(pCur.pBtree.db.mutex));
+ // Not needed in C# // Debug.Assert( pRes != 0 );
+ Debug.Assert((pIdxKey == null) == (pCur.pKeyInfo == null));
+
+ /* If the cursor is already positioned at the point we are trying
+ ** to move to, then just return without doing any work */
+ if (pCur.eState == CURSOR_VALID && pCur.validNKey
+ && pCur.apPage[0].intKey != 0
+ ) {
+ if (pCur.info.nKey == intKey) {
+ pRes = 0;
+ return SQLITE_OK;
+ }
+ if (pCur.atLast != 0 && pCur.info.nKey < intKey) {
+ pRes = -1;
+ return SQLITE_OK;
+ }
+ }
+ rc = moveToRoot(pCur);
+ if (rc != 0) {
+ return rc;
+ }
+ Debug.Assert(pCur.apPage[pCur.iPage] != null);
+ Debug.Assert(pCur.apPage[pCur.iPage].isInit != 0);
+ Debug.Assert(pCur.apPage[pCur.iPage].nCell > 0 || pCur.eState == CURSOR_INVALID);
+ if (pCur.eState == CURSOR_INVALID) {
+ pRes = -1;
+ Debug.Assert(pCur.apPage[pCur.iPage].nCell == 0);
+ return SQLITE_OK;
+ }
+ Debug.Assert(pCur.apPage[0].intKey != 0 || pIdxKey != null);
+ for (; ; )
+ {
+ int lwr, upr, idx;
+ Pgno chldPg;
+ MemPage pPage = pCur.apPage[pCur.iPage];
+ int c;
+
+ /* pPage.nCell must be greater than zero. If this is the root-page
+ ** the cursor would have been INVALID above and this for(;;) loop
+ ** not run. If this is not the root-page, then the moveToChild() routine
+ ** would have already detected db corruption. Similarly, pPage must
+ ** be the right kind (index or table) of b-tree page. Otherwise
+ ** a moveToChild() or moveToRoot() call would have detected corruption. */
+ Debug.Assert(pPage.nCell > 0);
+ Debug.Assert(pPage.intKey == ((pIdxKey == null) ? 1 : 0));
+ lwr = 0;
+ upr = pPage.nCell - 1;
+ if (biasRight != 0) {
+ pCur.aiIdx[pCur.iPage] = (u16)(idx = upr);
+ } else {
+ pCur.aiIdx[pCur.iPage] = (u16)(idx = (upr + lwr) / 2);
+ }
+ for (; ; )
+ {
+ int pCell; /* Pointer to current cell in pPage */
+
+ Debug.Assert(idx == pCur.aiIdx[pCur.iPage]);
+ pCur.info.nSize = 0;
+ pCell = findCell(pPage, idx) + pPage.childPtrSize;
+ if (pPage.intKey != 0) {
+ i64 nCellKey = 0;
+ if (pPage.hasData != 0) {
+ u32 Dummy0 = 0;
+ pCell += getVarint32(pPage.aData, pCell, out Dummy0);
+ }
+ getVarint(pPage.aData, pCell, out nCellKey);
+ if (nCellKey == intKey) {
+ c = 0;
+ } else if (nCellKey < intKey) {
+ c = -1;
+ } else {
+ Debug.Assert(nCellKey > intKey);
+ c = +1;
+ }
+ pCur.validNKey = true;
+ pCur.info.nKey = nCellKey;
+ } else {
+ /* The maximum supported page-size is 65536 bytes. This means that
+ ** the maximum number of record bytes stored on an index B-Tree
+ ** page is less than 16384 bytes and may be stored as a 2-byte
+ ** varint. This information is used to attempt to avoid parsing
+ ** the entire cell by checking for the cases where the record is
+ ** stored entirely within the b-tree page by inspecting the first
+ ** 2 bytes of the cell.
+ */
+ int nCell = pPage.aData[pCell + 0]; //pCell[0];
+ if (0 == (nCell & 0x80) && nCell <= pPage.maxLocal) {
+ /* This branch runs if the record-size field of the cell is a
+ ** single byte varint and the record fits entirely on the main
+ ** b-tree page. */
+ c = sqlite3VdbeRecordCompare(nCell, pPage.aData, pCell + 1, pIdxKey); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[1], pIdxKey );
+ } else if (0 == (pPage.aData[pCell + 1] & 0x80)//!(pCell[1] & 0x80)
+ && (nCell = ((nCell & 0x7f) << 7) + pPage.aData[pCell + 1]) <= pPage.maxLocal//pCell[1])<=pPage.maxLocal
+ ) {
+ /* The record-size field is a 2 byte varint and the record
+ ** fits entirely on the main b-tree page. */
+ c = sqlite3VdbeRecordCompare(nCell, pPage.aData, pCell + 2, pIdxKey); //c = sqlite3VdbeRecordCompare( nCell, (void*)&pCell[2], pIdxKey );
+ } else {
+ /* The record flows over onto one or more overflow pages. In
+ ** this case the whole cell needs to be parsed, a buffer allocated
+ ** and accessPayload() used to retrieve the record into the
+ ** buffer before VdbeRecordCompare() can be called. */
+ u8[] pCellKey;
+ u8[] pCellBody = new u8[pPage.aData.Length - pCell + pPage.childPtrSize];
+ Buffer.BlockCopy(pPage.aData, pCell - pPage.childPtrSize, pCellBody, 0, pCellBody.Length);// u8 * const pCellBody = pCell - pPage->childPtrSize;
+ btreeParseCellPtr(pPage, pCellBody, ref pCur.info);
+ nCell = (int)pCur.info.nKey;
+ pCellKey = sqlite3Malloc(nCell);
+ //if ( pCellKey == null )
+ //{
+ // rc = SQLITE_NOMEM;
+ // goto moveto_finish;
+ //}
+ rc = accessPayload(pCur, 0, (u32)nCell, pCellKey, 0);
+ if (rc != 0) {
+ pCellKey = null;// sqlite3_free(ref pCellKey );
+ goto moveto_finish;
+ }
+ c = sqlite3VdbeRecordCompare(nCell, pCellKey, pIdxKey);
+ pCellKey = null;// sqlite3_free(ref pCellKey );
+ }
+ }
+ if (c == 0) {
+ if (pPage.intKey != 0 && 0 == pPage.leaf) {
+ lwr = idx;
+ upr = lwr - 1;
+ break;
+ } else {
+ pRes = 0;
+ rc = SQLITE_OK;
+ goto moveto_finish;
+ }
+ }
+ if (c < 0) {
+ lwr = idx + 1;
+ } else {
+ upr = idx - 1;
+ }
+ if (lwr > upr) {
+ break;
+ }
+ pCur.aiIdx[pCur.iPage] = (u16)(idx = (lwr + upr) / 2);
+ }
+ Debug.Assert(lwr == upr + 1);
+ Debug.Assert(pPage.isInit != 0);
+ if (pPage.leaf != 0) {
+ chldPg = 0;
+ } else if (lwr >= pPage.nCell) {
+ chldPg = sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8);
+ } else {
+ chldPg = sqlite3Get4byte(pPage.aData, findCell(pPage, lwr));
+ }
+ if (chldPg == 0) {
+ Debug.Assert(pCur.aiIdx[pCur.iPage] < pCur.apPage[pCur.iPage].nCell);
+ pRes = c;
+ rc = SQLITE_OK;
+ goto moveto_finish;
+ }
+ pCur.aiIdx[pCur.iPage] = (u16)lwr;
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+ rc = moveToChild(pCur, chldPg);
+ if (rc != 0)
+ goto moveto_finish;
+ }
+ moveto_finish:
+ return rc;
+ }
-/*
-** Return TRUE if the cursor is not pointing at an entry of the table.
-**
-** TRUE will be returned after a call to sqlite3BtreeNext() moves
-** past the last entry in the table or sqlite3BtreePrev() moves past
-** the first entry. TRUE is also returned if the table is empty.
-*/
-static bool sqlite3BtreeEof( BtCursor pCur )
-{
- /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
- ** have been deleted? This API will need to change to return an error code
- ** as well as the boolean result value.
- */
- return ( CURSOR_VALID != pCur.eState );
-}
-/*
-** Advance the cursor to the next entry in the database. If
-** successful then set pRes=0. If the cursor
-** was already pointing to the last entry in the database before
-** this routine was called, then set pRes=1.
-*/
-static int sqlite3BtreeNext( BtCursor pCur, ref int pRes )
-{
- int rc;
- int idx;
- MemPage pPage;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- rc = restoreCursorPosition( pCur );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- // Not needed in C# // Debug.Assert( pRes != 0 );
- if ( CURSOR_INVALID == pCur.eState )
- {
- pRes = 1;
- return SQLITE_OK;
- }
- if ( pCur.skipNext > 0 )
- {
- pCur.skipNext = 0;
- pRes = 0;
- return SQLITE_OK;
- }
- pCur.skipNext = 0;
-
- pPage = pCur.apPage[pCur.iPage];
- idx = ++pCur.aiIdx[pCur.iPage];
- Debug.Assert( pPage.isInit != 0 );
- Debug.Assert( idx <= pPage.nCell );
-
- pCur.info.nSize = 0;
- pCur.validNKey = false;
- if ( idx >= pPage.nCell )
- {
- if ( 0 == pPage.leaf )
- {
- rc = moveToChild( pCur, sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 ) );
- if ( rc != 0 )
- return rc;
- rc = moveToLeftmost( pCur );
- pRes = 0;
- return rc;
- }
- do
- {
- if ( pCur.iPage == 0 )
- {
- pRes = 1;
- pCur.eState = CURSOR_INVALID;
- return SQLITE_OK;
- }
- moveToParent( pCur );
- pPage = pCur.apPage[pCur.iPage];
- } while ( pCur.aiIdx[pCur.iPage] >= pPage.nCell );
- pRes = 0;
- if ( pPage.intKey != 0 )
- {
- rc = sqlite3BtreeNext( pCur, ref pRes );
- }
- else
- {
- rc = SQLITE_OK;
- }
- return rc;
- }
- pRes = 0;
- if ( pPage.leaf != 0 )
- {
- return SQLITE_OK;
- }
- rc = moveToLeftmost( pCur );
- return rc;
-}
+ /*
+ ** Return TRUE if the cursor is not pointing at an entry of the table.
+ **
+ ** TRUE will be returned after a call to sqlite3BtreeNext() moves
+ ** past the last entry in the table or sqlite3BtreePrev() moves past
+ ** the first entry. TRUE is also returned if the table is empty.
+ */
+ static bool sqlite3BtreeEof(BtCursor pCur) {
+ /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
+ ** have been deleted? This API will need to change to return an error code
+ ** as well as the boolean result value.
+ */
+ return (CURSOR_VALID != pCur.eState);
+ }
+ /*
+ ** Advance the cursor to the next entry in the database. If
+ ** successful then set pRes=0. If the cursor
+ ** was already pointing to the last entry in the database before
+ ** this routine was called, then set pRes=1.
+ */
+ static int sqlite3BtreeNext(BtCursor pCur, ref int pRes) {
+ int rc;
+ int idx;
+ MemPage pPage;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ rc = restoreCursorPosition(pCur);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ // Not needed in C# // Debug.Assert( pRes != 0 );
+ if (CURSOR_INVALID == pCur.eState) {
+ pRes = 1;
+ return SQLITE_OK;
+ }
+ if (pCur.skipNext > 0) {
+ pCur.skipNext = 0;
+ pRes = 0;
+ return SQLITE_OK;
+ }
+ pCur.skipNext = 0;
+
+ pPage = pCur.apPage[pCur.iPage];
+ idx = ++pCur.aiIdx[pCur.iPage];
+ Debug.Assert(pPage.isInit != 0);
+ Debug.Assert(idx <= pPage.nCell);
+
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+ if (idx >= pPage.nCell) {
+ if (0 == pPage.leaf) {
+ rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8));
+ if (rc != 0)
+ return rc;
+ rc = moveToLeftmost(pCur);
+ pRes = 0;
+ return rc;
+ }
+ do {
+ if (pCur.iPage == 0) {
+ pRes = 1;
+ pCur.eState = CURSOR_INVALID;
+ return SQLITE_OK;
+ }
+ moveToParent(pCur);
+ pPage = pCur.apPage[pCur.iPage];
+ } while (pCur.aiIdx[pCur.iPage] >= pPage.nCell);
+ pRes = 0;
+ if (pPage.intKey != 0) {
+ rc = sqlite3BtreeNext(pCur, ref pRes);
+ } else {
+ rc = SQLITE_OK;
+ }
+ return rc;
+ }
+ pRes = 0;
+ if (pPage.leaf != 0) {
+ return SQLITE_OK;
+ }
+ rc = moveToLeftmost(pCur);
+ return rc;
+ }
-/*
-** Step the cursor to the back to the previous entry in the database. If
-** successful then set pRes=0. If the cursor
-** was already pointing to the first entry in the database before
-** this routine was called, then set pRes=1.
-*/
-static int sqlite3BtreePrevious( BtCursor pCur, ref int pRes )
-{
- int rc;
- MemPage pPage;
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- rc = restoreCursorPosition( pCur );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- pCur.atLast = 0;
- if ( CURSOR_INVALID == pCur.eState )
- {
- pRes = 1;
- return SQLITE_OK;
- }
- if ( pCur.skipNext < 0 )
- {
- pCur.skipNext = 0;
- pRes = 0;
- return SQLITE_OK;
- }
- pCur.skipNext = 0;
-
- pPage = pCur.apPage[pCur.iPage];
- Debug.Assert( pPage.isInit != 0 );
- if ( 0 == pPage.leaf )
- {
- int idx = pCur.aiIdx[pCur.iPage];
- rc = moveToChild( pCur, sqlite3Get4byte( pPage.aData, findCell( pPage, idx ) ) );
- if ( rc != 0 )
- {
- return rc;
- }
- rc = moveToRightmost( pCur );
- }
- else
- {
- while ( pCur.aiIdx[pCur.iPage] == 0 )
- {
- if ( pCur.iPage == 0 )
- {
- pCur.eState = CURSOR_INVALID;
- pRes = 1;
- return SQLITE_OK;
- }
- moveToParent( pCur );
- }
- pCur.info.nSize = 0;
- pCur.validNKey = false;
- pCur.aiIdx[pCur.iPage]--;
- pPage = pCur.apPage[pCur.iPage];
- if ( pPage.intKey != 0 && 0 == pPage.leaf )
- {
- rc = sqlite3BtreePrevious( pCur, ref pRes );
- }
- else
- {
- rc = SQLITE_OK;
- }
- }
- pRes = 0;
- return rc;
-}
+ /*
+ ** Step the cursor to the back to the previous entry in the database. If
+ ** successful then set pRes=0. If the cursor
+ ** was already pointing to the first entry in the database before
+ ** this routine was called, then set pRes=1.
+ */
+ static int sqlite3BtreePrevious(BtCursor pCur, ref int pRes) {
+ int rc;
+ MemPage pPage;
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ rc = restoreCursorPosition(pCur);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ pCur.atLast = 0;
+ if (CURSOR_INVALID == pCur.eState) {
+ pRes = 1;
+ return SQLITE_OK;
+ }
+ if (pCur.skipNext < 0) {
+ pCur.skipNext = 0;
+ pRes = 0;
+ return SQLITE_OK;
+ }
+ pCur.skipNext = 0;
+
+ pPage = pCur.apPage[pCur.iPage];
+ Debug.Assert(pPage.isInit != 0);
+ if (0 == pPage.leaf) {
+ int idx = pCur.aiIdx[pCur.iPage];
+ rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, findCell(pPage, idx)));
+ if (rc != 0) {
+ return rc;
+ }
+ rc = moveToRightmost(pCur);
+ } else {
+ while (pCur.aiIdx[pCur.iPage] == 0) {
+ if (pCur.iPage == 0) {
+ pCur.eState = CURSOR_INVALID;
+ pRes = 1;
+ return SQLITE_OK;
+ }
+ moveToParent(pCur);
+ }
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+
+ pCur.aiIdx[pCur.iPage]--;
+ pPage = pCur.apPage[pCur.iPage];
+ if (pPage.intKey != 0 && 0 == pPage.leaf) {
+ rc = sqlite3BtreePrevious(pCur, ref pRes);
+ } else {
+ rc = SQLITE_OK;
+ }
+ }
+ pRes = 0;
+ return rc;
+ }
-/*
-** Allocate a new page from the database file.
-**
-** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
-** has already been called on the new page.) The new page has also
-** been referenced and the calling routine is responsible for calling
-** sqlite3PagerUnref() on the new page when it is done.
-**
-** SQLITE_OK is returned on success. Any other return value indicates
-** an error. ppPage and pPgno are undefined in the event of an error.
-** Do not invoke sqlite3PagerUnref() on ppPage if an error is returned.
-**
-** If the "nearby" parameter is not 0, then a (feeble) effort is made to
-** locate a page close to the page number "nearby". This can be used in an
-** attempt to keep related pages close to each other in the database file,
-** which in turn can make database access faster.
-**
-** If the "exact" parameter is not 0, and the page-number nearby exists
-** anywhere on the free-list, then it is guarenteed to be returned. This
-** is only used by auto-vacuum databases when allocating a new table.
-*/
-static int allocateBtreePage(
-BtShared pBt,
-ref MemPage ppPage,
-ref Pgno pPgno,
-Pgno nearby,
-u8 exact
-)
-{
- MemPage pPage1;
- int rc;
- u32 n; /* Number of pages on the freelist */
- u32 k; /* Number of leaves on the trunk of the freelist */
- MemPage pTrunk = null;
- MemPage pPrevTrunk = null;
- Pgno mxPage; /* Total size of the database file */
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- pPage1 = pBt.pPage1;
- mxPage = btreePagecount( pBt );
- n = sqlite3Get4byte( pPage1.aData, 36 );
- testcase( n == mxPage - 1 );
- if ( n >= mxPage )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- if ( n > 0 )
- {
- /* There are pages on the freelist. Reuse one of those pages. */
- Pgno iTrunk;
- u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
-
- /* If the 'exact' parameter was true and a query of the pointer-map
- ** shows that the page 'nearby' is somewhere on the free-list, then
- ** the entire-list will be searched for that page.
- */
+ /*
+ ** Allocate a new page from the database file.
+ **
+ ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
+ ** has already been called on the new page.) The new page has also
+ ** been referenced and the calling routine is responsible for calling
+ ** sqlite3PagerUnref() on the new page when it is done.
+ **
+ ** SQLITE_OK is returned on success. Any other return value indicates
+ ** an error. ppPage and pPgno are undefined in the event of an error.
+ ** Do not invoke sqlite3PagerUnref() on ppPage if an error is returned.
+ **
+ ** If the "nearby" parameter is not 0, then a (feeble) effort is made to
+ ** locate a page close to the page number "nearby". This can be used in an
+ ** attempt to keep related pages close to each other in the database file,
+ ** which in turn can make database access faster.
+ **
+ ** If the "exact" parameter is not 0, and the page-number nearby exists
+ ** anywhere on the free-list, then it is guarenteed to be returned. This
+ ** is only used by auto-vacuum databases when allocating a new table.
+ */
+ static int allocateBtreePage(
+ BtShared pBt,
+ ref MemPage ppPage,
+ ref Pgno pPgno,
+ Pgno nearby,
+ u8 exact
+ ) {
+ MemPage pPage1;
+ int rc;
+ u32 n; /* Number of pages on the freelist */
+ u32 k; /* Number of leaves on the trunk of the freelist */
+ MemPage pTrunk = null;
+ MemPage pPrevTrunk = null;
+ Pgno mxPage; /* Total size of the database file */
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ pPage1 = pBt.pPage1;
+ mxPage = btreePagecount(pBt);
+ n = sqlite3Get4byte(pPage1.aData, 36);
+ testcase(n == mxPage - 1);
+ if (n >= mxPage) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ if (n > 0) {
+ /* There are pages on the freelist. Reuse one of those pages. */
+ Pgno iTrunk;
+ u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
+
+ /* If the 'exact' parameter was true and a query of the pointer-map
+ ** shows that the page 'nearby' is somewhere on the free-list, then
+ ** the entire-list will be searched for that page.
+ */
#if !SQLITE_OMIT_AUTOVACUUM
- if ( exact != 0 && nearby <= mxPage )
- {
- u8 eType = 0;
- Debug.Assert( nearby > 0 );
- Debug.Assert( pBt.autoVacuum );
- u32 Dummy0 = 0;
- rc = ptrmapGet( pBt, nearby, ref eType, ref Dummy0 );
- if ( rc != 0 )
- return rc;
- if ( eType == PTRMAP_FREEPAGE )
- {
- searchList = 1;
- }
- pPgno = nearby;
- }
+ if (exact != 0 && nearby <= mxPage) {
+ u8 eType = 0;
+ Debug.Assert(nearby > 0);
+ Debug.Assert(pBt.autoVacuum);
+ u32 Dummy0 = 0;
+ rc = ptrmapGet(pBt, nearby, ref eType, ref Dummy0);
+ if (rc != 0)
+ return rc;
+ if (eType == PTRMAP_FREEPAGE) {
+ searchList = 1;
+ }
+ pPgno = nearby;
+ }
#endif
- /* Decrement the free-list count by 1. Set iTrunk to the index of the
-** first free-list trunk page. iPrevTrunk is initially 1.
-*/
- rc = sqlite3PagerWrite( pPage1.pDbPage );
- if ( rc != 0 )
- return rc;
- sqlite3Put4byte( pPage1.aData, (u32)36, n - 1 );
-
- /* The code within this loop is run only once if the 'searchList' variable
- ** is not true. Otherwise, it runs once for each trunk-page on the
- ** free-list until the page 'nearby' is located.
- */
- do
- {
- pPrevTrunk = pTrunk;
- if ( pPrevTrunk != null )
- {
- iTrunk = sqlite3Get4byte( pPrevTrunk.aData, 0 );
- }
- else
- {
- iTrunk = sqlite3Get4byte( pPage1.aData, 32 );
- }
- testcase( iTrunk == mxPage );
- if ( iTrunk > mxPage )
- {
- rc = SQLITE_CORRUPT_BKPT();
- }
- else
- {
- rc = btreeGetPage( pBt, iTrunk, ref pTrunk, 0 );
- }
- if ( rc != 0 )
- {
- pTrunk = null;
- goto end_allocate_page;
- }
-
- k = sqlite3Get4byte( pTrunk.aData, 4 ); /* # of leaves on this trunk page */
- if ( k == 0 && 0 == searchList )
- {
- /* The trunk has no leaves and the list is not being searched.
- ** So extract the trunk page itself and use it as the newly
- ** allocated page */
- Debug.Assert( pPrevTrunk == null );
- rc = sqlite3PagerWrite( pTrunk.pDbPage );
- if ( rc != 0 )
- {
- goto end_allocate_page;
- }
- pPgno = iTrunk;
- Buffer.BlockCopy( pTrunk.aData, 0, pPage1.aData, 32, 4 );//memcpy( pPage1.aData[32], ref pTrunk.aData[0], 4 );
- ppPage = pTrunk;
- pTrunk = null;
- TRACE( "ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1 );
- }
- else if ( k > (u32)( pBt.usableSize / 4 - 2 ) )
- {
- /* Value of k is out of range. Database corruption */
- rc = SQLITE_CORRUPT_BKPT();
- goto end_allocate_page;
+ /* Decrement the free-list count by 1. Set iTrunk to the index of the
+ ** first free-list trunk page. iPrevTrunk is initially 1.
+ */
+ rc = sqlite3PagerWrite(pPage1.pDbPage);
+ if (rc != 0)
+ return rc;
+ sqlite3Put4byte(pPage1.aData, (u32)36, n - 1);
+
+ /* The code within this loop is run only once if the 'searchList' variable
+ ** is not true. Otherwise, it runs once for each trunk-page on the
+ ** free-list until the page 'nearby' is located.
+ */
+ do {
+ pPrevTrunk = pTrunk;
+ if (pPrevTrunk != null) {
+ iTrunk = sqlite3Get4byte(pPrevTrunk.aData, 0);
+ } else {
+ iTrunk = sqlite3Get4byte(pPage1.aData, 32);
+ }
+ testcase(iTrunk == mxPage);
+ if (iTrunk > mxPage) {
+ rc = SQLITE_CORRUPT_BKPT();
+ } else {
+ rc = btreeGetPage(pBt, iTrunk, ref pTrunk, 0);
+ }
+ if (rc != 0) {
+ pTrunk = null;
+ goto end_allocate_page;
+ }
+
+ k = sqlite3Get4byte(pTrunk.aData, 4); /* # of leaves on this trunk page */
+ if (k == 0 && 0 == searchList) {
+ /* The trunk has no leaves and the list is not being searched.
+ ** So extract the trunk page itself and use it as the newly
+ ** allocated page */
+ Debug.Assert(pPrevTrunk == null);
+ rc = sqlite3PagerWrite(pTrunk.pDbPage);
+ if (rc != 0) {
+ goto end_allocate_page;
+ }
+ pPgno = iTrunk;
+ Buffer.BlockCopy(pTrunk.aData, 0, pPage1.aData, 32, 4);//memcpy( pPage1.aData[32], ref pTrunk.aData[0], 4 );
+ ppPage = pTrunk;
+ pTrunk = null;
+ TRACE("ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1);
+ } else if (k > (u32)(pBt.usableSize / 4 - 2)) {
+ /* Value of k is out of range. Database corruption */
+ rc = SQLITE_CORRUPT_BKPT();
+ goto end_allocate_page;
#if !SQLITE_OMIT_AUTOVACUUM
- }
- else if ( searchList != 0 && nearby == iTrunk )
- {
- /* The list is being searched and this trunk page is the page
- ** to allocate, regardless of whether it has leaves.
- */
- Debug.Assert( pPgno == iTrunk );
- ppPage = pTrunk;
- searchList = 0;
- rc = sqlite3PagerWrite( pTrunk.pDbPage );
- if ( rc != 0 )
- {
- goto end_allocate_page;
- }
- if ( k == 0 )
- {
- if ( null == pPrevTrunk )
- {
- //memcpy(pPage1.aData[32], pTrunk.aData[0], 4);
- pPage1.aData[32 + 0] = pTrunk.aData[0 + 0];
- pPage1.aData[32 + 1] = pTrunk.aData[0 + 1];
- pPage1.aData[32 + 2] = pTrunk.aData[0 + 2];
- pPage1.aData[32 + 3] = pTrunk.aData[0 + 3];
- }
- else
- {
- rc = sqlite3PagerWrite( pPrevTrunk.pDbPage );
- if ( rc != SQLITE_OK )
- {
- goto end_allocate_page;
- }
- //memcpy(pPrevTrunk.aData[0], pTrunk.aData[0], 4);
- pPrevTrunk.aData[0 + 0] = pTrunk.aData[0 + 0];
- pPrevTrunk.aData[0 + 1] = pTrunk.aData[0 + 1];
- pPrevTrunk.aData[0 + 2] = pTrunk.aData[0 + 2];
- pPrevTrunk.aData[0 + 3] = pTrunk.aData[0 + 3];
- }
- }
- else
- {
- /* The trunk page is required by the caller but it contains
- ** pointers to free-list leaves. The first leaf becomes a trunk
- ** page in this case.
- */
- MemPage pNewTrunk = new MemPage();
- Pgno iNewTrunk = sqlite3Get4byte( pTrunk.aData, 8 );
- if ( iNewTrunk > mxPage )
- {
- rc = SQLITE_CORRUPT_BKPT();
- goto end_allocate_page;
- }
- testcase( iNewTrunk == mxPage );
- rc = btreeGetPage( pBt, iNewTrunk, ref pNewTrunk, 0 );
- if ( rc != SQLITE_OK )
- {
- goto end_allocate_page;
- }
- rc = sqlite3PagerWrite( pNewTrunk.pDbPage );
- if ( rc != SQLITE_OK )
- {
- releasePage( pNewTrunk );
- goto end_allocate_page;
- }
- //memcpy(pNewTrunk.aData[0], pTrunk.aData[0], 4);
- pNewTrunk.aData[0 + 0] = pTrunk.aData[0 + 0];
- pNewTrunk.aData[0 + 1] = pTrunk.aData[0 + 1];
- pNewTrunk.aData[0 + 2] = pTrunk.aData[0 + 2];
- pNewTrunk.aData[0 + 3] = pTrunk.aData[0 + 3];
- sqlite3Put4byte( pNewTrunk.aData, (u32)4, (u32)( k - 1 ) );
- Buffer.BlockCopy( pTrunk.aData, 12, pNewTrunk.aData, 8, (int)( k - 1 ) * 4 );//memcpy( pNewTrunk.aData[8], ref pTrunk.aData[12], ( k - 1 ) * 4 );
- releasePage( pNewTrunk );
- if ( null == pPrevTrunk )
- {
- Debug.Assert( sqlite3PagerIswriteable( pPage1.pDbPage ) );
- sqlite3Put4byte( pPage1.aData, (u32)32, iNewTrunk );
- }
- else
- {
- rc = sqlite3PagerWrite( pPrevTrunk.pDbPage );
- if ( rc != 0 )
- {
- goto end_allocate_page;
- }
- sqlite3Put4byte( pPrevTrunk.aData, (u32)0, iNewTrunk );
- }
- }
- pTrunk = null;
- TRACE( "ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1 );
+ } else if (searchList != 0 && nearby == iTrunk) {
+ /* The list is being searched and this trunk page is the page
+ ** to allocate, regardless of whether it has leaves.
+ */
+ Debug.Assert(pPgno == iTrunk);
+ ppPage = pTrunk;
+ searchList = 0;
+ rc = sqlite3PagerWrite(pTrunk.pDbPage);
+ if (rc != 0) {
+ goto end_allocate_page;
+ }
+ if (k == 0) {
+ if (null == pPrevTrunk) {
+ //memcpy(pPage1.aData[32], pTrunk.aData[0], 4);
+ pPage1.aData[32 + 0] = pTrunk.aData[0 + 0];
+ pPage1.aData[32 + 1] = pTrunk.aData[0 + 1];
+ pPage1.aData[32 + 2] = pTrunk.aData[0 + 2];
+ pPage1.aData[32 + 3] = pTrunk.aData[0 + 3];
+ } else {
+ rc = sqlite3PagerWrite(pPrevTrunk.pDbPage);
+ if (rc != SQLITE_OK) {
+ goto end_allocate_page;
+ }
+ //memcpy(pPrevTrunk.aData[0], pTrunk.aData[0], 4);
+ pPrevTrunk.aData[0 + 0] = pTrunk.aData[0 + 0];
+ pPrevTrunk.aData[0 + 1] = pTrunk.aData[0 + 1];
+ pPrevTrunk.aData[0 + 2] = pTrunk.aData[0 + 2];
+ pPrevTrunk.aData[0 + 3] = pTrunk.aData[0 + 3];
+ }
+ } else {
+ /* The trunk page is required by the caller but it contains
+ ** pointers to free-list leaves. The first leaf becomes a trunk
+ ** page in this case.
+ */
+ MemPage pNewTrunk = new MemPage();
+ Pgno iNewTrunk = sqlite3Get4byte(pTrunk.aData, 8);
+ if (iNewTrunk > mxPage) {
+ rc = SQLITE_CORRUPT_BKPT();
+ goto end_allocate_page;
+ }
+ testcase(iNewTrunk == mxPage);
+ rc = btreeGetPage(pBt, iNewTrunk, ref pNewTrunk, 0);
+ if (rc != SQLITE_OK) {
+ goto end_allocate_page;
+ }
+ rc = sqlite3PagerWrite(pNewTrunk.pDbPage);
+ if (rc != SQLITE_OK) {
+ releasePage(pNewTrunk);
+ goto end_allocate_page;
+ }
+ //memcpy(pNewTrunk.aData[0], pTrunk.aData[0], 4);
+ pNewTrunk.aData[0 + 0] = pTrunk.aData[0 + 0];
+ pNewTrunk.aData[0 + 1] = pTrunk.aData[0 + 1];
+ pNewTrunk.aData[0 + 2] = pTrunk.aData[0 + 2];
+ pNewTrunk.aData[0 + 3] = pTrunk.aData[0 + 3];
+ sqlite3Put4byte(pNewTrunk.aData, (u32)4, (u32)(k - 1));
+ Buffer.BlockCopy(pTrunk.aData, 12, pNewTrunk.aData, 8, (int)(k - 1) * 4);//memcpy( pNewTrunk.aData[8], ref pTrunk.aData[12], ( k - 1 ) * 4 );
+ releasePage(pNewTrunk);
+ if (null == pPrevTrunk) {
+ Debug.Assert(sqlite3PagerIswriteable(pPage1.pDbPage));
+ sqlite3Put4byte(pPage1.aData, (u32)32, iNewTrunk);
+ } else {
+ rc = sqlite3PagerWrite(pPrevTrunk.pDbPage);
+ if (rc != 0) {
+ goto end_allocate_page;
+ }
+ sqlite3Put4byte(pPrevTrunk.aData, (u32)0, iNewTrunk);
+ }
+ }
+ pTrunk = null;
+ TRACE("ALLOCATE: %d trunk - %d free pages left\n", pPgno, n - 1);
#endif
- }
- else if ( k > 0 )
- {
- /* Extract a leaf from the trunk */
- u32 closest;
- Pgno iPage;
- byte[] aData = pTrunk.aData;
- if ( nearby > 0 )
- {
- u32 i;
- int dist;
- closest = 0;
- dist = sqlite3AbsInt32( (int)(sqlite3Get4byte( aData, 8 ) - nearby ));
- for ( i = 1; i < k; i++ )
- {
- int d2 = sqlite3AbsInt32( (int)(sqlite3Get4byte( aData, 8 + i * 4 ) - nearby ));
- if ( d2 < dist )
- {
- closest = i;
- dist = d2;
- }
- }
- }
- else
- {
- closest = 0;
- }
-
- iPage = sqlite3Get4byte( aData, 8 + closest * 4 );
- testcase( iPage == mxPage );
- if ( iPage > mxPage )
- {
- rc = SQLITE_CORRUPT_BKPT();
- goto end_allocate_page;
- }
- testcase( iPage == mxPage );
- if ( 0 == searchList || iPage == nearby )
- {
- int noContent;
- pPgno = iPage;
- TRACE( "ALLOCATE: %d was leaf %d of %d on trunk %d" +
- ": %d more free pages\n",
- pPgno, closest + 1, k, pTrunk.pgno, n - 1 );
- rc = sqlite3PagerWrite( pTrunk.pDbPage );
- if ( rc != 0)
- goto end_allocate_page;
- if ( closest < k - 1 )
- {
- Buffer.BlockCopy( aData, (int)( 4 + k * 4 ), aData, 8 + (int)closest * 4, 4 );//memcpy( aData[8 + closest * 4], ref aData[4 + k * 4], 4 );
- }
- sqlite3Put4byte( aData, (u32)4, ( k - 1 ) );// sqlite3Put4byte( aData, 4, k - 1 );
- noContent = !btreeGetHasContent( pBt, pPgno ) ? 1 : 0;
- rc = btreeGetPage( pBt, pPgno, ref ppPage, noContent );
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3PagerWrite( ( ppPage ).pDbPage );
- if ( rc != SQLITE_OK )
- {
- releasePage( ppPage );
- }
- }
- searchList = 0;
- }
- }
- releasePage( pPrevTrunk );
- pPrevTrunk = null;
- } while ( searchList != 0 );
- }
- else
- {
- /* There are no pages on the freelist, so create a new page at the
- ** end of the file */
- rc = sqlite3PagerWrite( pBt.pPage1.pDbPage );
- if ( rc != 0 )
- return rc;
- pBt.nPage++;
- if ( pBt.nPage == PENDING_BYTE_PAGE( pBt ) )
- pBt.nPage++;
+ } else if (k > 0) {
+ /* Extract a leaf from the trunk */
+ u32 closest;
+ Pgno iPage;
+ byte[] aData = pTrunk.aData;
+ if (nearby > 0) {
+ u32 i;
+ int dist;
+ closest = 0;
+ dist = sqlite3AbsInt32((int)(sqlite3Get4byte(aData, 8) - nearby));
+ for (i = 1; i < k; i++) {
+ int d2 = sqlite3AbsInt32((int)(sqlite3Get4byte(aData, 8 + i * 4) - nearby));
+ if (d2 < dist) {
+ closest = i;
+ dist = d2;
+ }
+ }
+ } else {
+ closest = 0;
+ }
+
+ iPage = sqlite3Get4byte(aData, 8 + closest * 4);
+ testcase(iPage == mxPage);
+ if (iPage > mxPage) {
+ rc = SQLITE_CORRUPT_BKPT();
+ goto end_allocate_page;
+ }
+ testcase(iPage == mxPage);
+ if (0 == searchList || iPage == nearby) {
+ int noContent;
+ pPgno = iPage;
+ TRACE("ALLOCATE: %d was leaf %d of %d on trunk %d" +
+ ": %d more free pages\n",
+ pPgno, closest + 1, k, pTrunk.pgno, n - 1);
+ rc = sqlite3PagerWrite(pTrunk.pDbPage);
+ if (rc != 0)
+ goto end_allocate_page;
+ if (closest < k - 1) {
+ Buffer.BlockCopy(aData, (int)(4 + k * 4), aData, 8 + (int)closest * 4, 4);//memcpy( aData[8 + closest * 4], ref aData[4 + k * 4], 4 );
+ }
+ sqlite3Put4byte(aData, (u32)4, (k - 1));// sqlite3Put4byte( aData, 4, k - 1 );
+ noContent = !btreeGetHasContent(pBt, pPgno) ? 1 : 0;
+ rc = btreeGetPage(pBt, pPgno, ref ppPage, noContent);
+ if (rc == SQLITE_OK) {
+ rc = sqlite3PagerWrite((ppPage).pDbPage);
+ if (rc != SQLITE_OK) {
+ releasePage(ppPage);
+ }
+ }
+ searchList = 0;
+ }
+ }
+ releasePage(pPrevTrunk);
+ pPrevTrunk = null;
+ } while (searchList != 0);
+ } else {
+ /* There are no pages on the freelist, so create a new page at the
+ ** end of the file */
+ rc = sqlite3PagerWrite(pBt.pPage1.pDbPage);
+ if (rc != 0)
+ return rc;
+ pBt.nPage++;
+ if (pBt.nPage == PENDING_BYTE_PAGE(pBt))
+ pBt.nPage++;
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pBt.autoVacuum && PTRMAP_ISPAGE( pBt, pBt.nPage ) )
- {
- /* If pPgno refers to a pointer-map page, allocate two new pages
- ** at the end of the file instead of one. The first allocated page
- ** becomes a new pointer-map page, the second is used by the caller.
- */
- MemPage pPg = null;
- TRACE( "ALLOCATE: %d from end of file (pointer-map page)\n", pPgno );
- Debug.Assert( pBt.nPage != PENDING_BYTE_PAGE( pBt ) );
- rc = btreeGetPage( pBt, pBt.nPage, ref pPg, 1 );
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3PagerWrite( pPg.pDbPage );
- releasePage( pPg );
- }
- if ( rc != 0 )
- return rc;
- pBt.nPage++;
- if ( pBt.nPage == PENDING_BYTE_PAGE( pBt ) )
- {
- pBt.nPage++;
- }
- }
+ if (pBt.autoVacuum && PTRMAP_ISPAGE(pBt, pBt.nPage)) {
+ /* If pPgno refers to a pointer-map page, allocate two new pages
+ ** at the end of the file instead of one. The first allocated page
+ ** becomes a new pointer-map page, the second is used by the caller.
+ */
+ MemPage pPg = null;
+ TRACE("ALLOCATE: %d from end of file (pointer-map page)\n", pPgno);
+ Debug.Assert(pBt.nPage != PENDING_BYTE_PAGE(pBt));
+ rc = btreeGetPage(pBt, pBt.nPage, ref pPg, 1);
+ if (rc == SQLITE_OK) {
+ rc = sqlite3PagerWrite(pPg.pDbPage);
+ releasePage(pPg);
+ }
+ if (rc != 0)
+ return rc;
+ pBt.nPage++;
+ if (pBt.nPage == PENDING_BYTE_PAGE(pBt)) {
+ pBt.nPage++;
+ }
+ }
#endif
- sqlite3Put4byte( pBt.pPage1.aData, (u32)28, pBt.nPage );
- pPgno = pBt.nPage;
-
- Debug.Assert( pPgno != PENDING_BYTE_PAGE( pBt ) );
- rc = btreeGetPage( pBt, pPgno, ref ppPage, 1 );
- if ( rc != 0 )
- return rc;
- rc = sqlite3PagerWrite( ( ppPage ).pDbPage );
- if ( rc != SQLITE_OK )
- {
- releasePage( ppPage );
- }
- TRACE( "ALLOCATE: %d from end of file\n", pPgno );
- }
+ sqlite3Put4byte(pBt.pPage1.aData, (u32)28, pBt.nPage);
+ pPgno = pBt.nPage;
+
+ Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt));
+ rc = btreeGetPage(pBt, pPgno, ref ppPage, 1);
+ if (rc != 0)
+ return rc;
+ rc = sqlite3PagerWrite((ppPage).pDbPage);
+ if (rc != SQLITE_OK) {
+ releasePage(ppPage);
+ }
+ TRACE("ALLOCATE: %d from end of file\n", pPgno);
+ }
- Debug.Assert( pPgno != PENDING_BYTE_PAGE( pBt ) );
+ Debug.Assert(pPgno != PENDING_BYTE_PAGE(pBt));
+
+ end_allocate_page:
+ releasePage(pTrunk);
+ releasePage(pPrevTrunk);
+ if (rc == SQLITE_OK) {
+ if (sqlite3PagerPageRefcount((ppPage).pDbPage) > 1) {
+ releasePage(ppPage);
+ return SQLITE_CORRUPT_BKPT();
+ }
+ (ppPage).isInit = 0;
+ } else {
+ ppPage = null;
+ }
+ Debug.Assert(rc != SQLITE_OK || sqlite3PagerIswriteable((ppPage).pDbPage));
+ return rc;
+ }
-end_allocate_page:
- releasePage( pTrunk );
- releasePage( pPrevTrunk );
- if ( rc == SQLITE_OK )
- {
- if ( sqlite3PagerPageRefcount( ( ppPage ).pDbPage ) > 1 )
- {
- releasePage( ppPage );
- return SQLITE_CORRUPT_BKPT();
- }
- ( ppPage ).isInit = 0;
- }
- else
- {
- ppPage = null;
- }
- Debug.Assert( rc != SQLITE_OK || sqlite3PagerIswriteable( ( ppPage ).pDbPage ) );
- return rc;
-}
+ /*
+ ** This function is used to add page iPage to the database file free-list.
+ ** It is assumed that the page is not already a part of the free-list.
+ **
+ ** The value passed as the second argument to this function is optional.
+ ** If the caller happens to have a pointer to the MemPage object
+ ** corresponding to page iPage handy, it may pass it as the second value.
+ ** Otherwise, it may pass NULL.
+ **
+ ** If a pointer to a MemPage object is passed as the second argument,
+ ** its reference count is not altered by this function.
+ */
+ static int freePage2(BtShared pBt, MemPage pMemPage, Pgno iPage) {
+ MemPage pTrunk = null; /* Free-list trunk page */
+ Pgno iTrunk = 0; /* Page number of free-list trunk page */
+ MemPage pPage1 = pBt.pPage1; /* Local reference to page 1 */
+ MemPage pPage; /* Page being freed. May be NULL. */
+ int rc; /* Return Code */
+ int nFree; /* Initial number of pages on free-list */
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(iPage > 1);
+ Debug.Assert(null == pMemPage || pMemPage.pgno == iPage);
+
+ if (pMemPage != null) {
+ pPage = pMemPage;
+ sqlite3PagerRef(pPage.pDbPage);
+ } else {
+ pPage = btreePageLookup(pBt, iPage);
+ }
-/*
-** This function is used to add page iPage to the database file free-list.
-** It is assumed that the page is not already a part of the free-list.
-**
-** The value passed as the second argument to this function is optional.
-** If the caller happens to have a pointer to the MemPage object
-** corresponding to page iPage handy, it may pass it as the second value.
-** Otherwise, it may pass NULL.
-**
-** If a pointer to a MemPage object is passed as the second argument,
-** its reference count is not altered by this function.
-*/
-static int freePage2( BtShared pBt, MemPage pMemPage, Pgno iPage )
-{
- MemPage pTrunk = null; /* Free-list trunk page */
- Pgno iTrunk = 0; /* Page number of free-list trunk page */
- MemPage pPage1 = pBt.pPage1; /* Local reference to page 1 */
- MemPage pPage; /* Page being freed. May be NULL. */
- int rc; /* Return Code */
- int nFree; /* Initial number of pages on free-list */
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( iPage > 1 );
- Debug.Assert( null == pMemPage || pMemPage.pgno == iPage );
-
- if ( pMemPage != null )
- {
- pPage = pMemPage;
- sqlite3PagerRef( pPage.pDbPage );
- }
- else
- {
- pPage = btreePageLookup( pBt, iPage );
- }
-
- /* Increment the free page count on pPage1 */
- rc = sqlite3PagerWrite( pPage1.pDbPage );
- if ( rc != 0 )
- goto freepage_out;
- nFree = (int)sqlite3Get4byte( pPage1.aData, 36 );
- sqlite3Put4byte( pPage1.aData, 36, nFree + 1 );
-
- if ( pBt.secureDelete )
- {
- /* If the secure_delete option is enabled, then
- ** always fully overwrite deleted information with zeros.
- */
- if ( ( null == pPage && ( ( rc = btreeGetPage( pBt, iPage, ref pPage, 0 ) ) != 0 ) )
- || ( ( rc = sqlite3PagerWrite( pPage.pDbPage ) ) != 0 )
- )
- {
- goto freepage_out;
- }
- Array.Clear( pPage.aData, 0, (int)pPage.pBt.pageSize );//memset(pPage->aData, 0, pPage->pBt->pageSize);
- }
+ /* Increment the free page count on pPage1 */
+ rc = sqlite3PagerWrite(pPage1.pDbPage);
+ if (rc != 0)
+ goto freepage_out;
+ nFree = (int)sqlite3Get4byte(pPage1.aData, 36);
+ sqlite3Put4byte(pPage1.aData, 36, nFree + 1);
+
+ if (pBt.secureDelete) {
+ /* If the secure_delete option is enabled, then
+ ** always fully overwrite deleted information with zeros.
+ */
+ if ((null == pPage && ((rc = btreeGetPage(pBt, iPage, ref pPage, 0)) != 0))
+ || ((rc = sqlite3PagerWrite(pPage.pDbPage)) != 0)
+ ) {
+ goto freepage_out;
+ }
+ Array.Clear(pPage.aData, 0, (int)pPage.pBt.pageSize);//memset(pPage->aData, 0, pPage->pBt->pageSize);
+ }
- /* If the database supports auto-vacuum, write an entry in the pointer-map
- ** to indicate that the page is free.
- */
+ /* If the database supports auto-vacuum, write an entry in the pointer-map
+ ** to indicate that the page is free.
+ */
#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM )
- if ( pBt.autoVacuum )
+ if (pBt.autoVacuum)
#else
if (false)
#endif
- {
- ptrmapPut( pBt, iPage, PTRMAP_FREEPAGE, 0, ref rc );
- if ( rc != 0 )
- goto freepage_out;
- }
-
- /* Now manipulate the actual database free-list structure. There are two
- ** possibilities. If the free-list is currently empty, or if the first
- ** trunk page in the free-list is full, then this page will become a
- ** new free-list trunk page. Otherwise, it will become a leaf of the
- ** first trunk page in the current free-list. This block tests if it
- ** is possible to add the page as a new free-list leaf.
- */
- if ( nFree != 0 )
- {
- u32 nLeaf; /* Initial number of leaf cells on trunk page */
-
- iTrunk = sqlite3Get4byte( pPage1.aData, 32 );
- rc = btreeGetPage( pBt, iTrunk, ref pTrunk, 0 );
- if ( rc != SQLITE_OK )
- {
- goto freepage_out;
- }
+ {
+ ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, ref rc);
+ if (rc != 0)
+ goto freepage_out;
+ }
- nLeaf = sqlite3Get4byte( pTrunk.aData, 4 );
- Debug.Assert( pBt.usableSize > 32 );
- if ( nLeaf > (u32)pBt.usableSize / 4 - 2 )
- {
- rc = SQLITE_CORRUPT_BKPT();
- goto freepage_out;
- }
- if ( nLeaf < (u32)pBt.usableSize / 4 - 8 )
- {
- /* In this case there is room on the trunk page to insert the page
- ** being freed as a new leaf.
- **
- ** Note that the trunk page is not really full until it contains
- ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
- ** coded. But due to a coding error in versions of SQLite prior to
- ** 3.6.0, databases with freelist trunk pages holding more than
- ** usableSize/4 - 8 entries will be reported as corrupt. In order
- ** to maintain backwards compatibility with older versions of SQLite,
- ** we will continue to restrict the number of entries to usableSize/4 - 8
- ** for now. At some point in the future (once everyone has upgraded
- ** to 3.6.0 or later) we should consider fixing the conditional above
- ** to read "usableSize/4-2" instead of "usableSize/4-8".
- */
- rc = sqlite3PagerWrite( pTrunk.pDbPage );
- if ( rc == SQLITE_OK )
- {
- sqlite3Put4byte( pTrunk.aData, (u32)4, nLeaf + 1 );
- sqlite3Put4byte( pTrunk.aData, (u32)8 + nLeaf * 4, iPage );
- if ( pPage != null && !pBt.secureDelete )
- {
- sqlite3PagerDontWrite( pPage.pDbPage );
- }
- rc = btreeSetHasContent( pBt, iPage );
- }
- TRACE( "FREE-PAGE: %d leaf on trunk page %d\n", iPage, pTrunk.pgno );
- goto freepage_out;
- }
- }
-
- /* If control flows to this point, then it was not possible to add the
- ** the page being freed as a leaf page of the first trunk in the free-list.
- ** Possibly because the free-list is empty, or possibly because the
- ** first trunk in the free-list is full. Either way, the page being freed
- ** will become the new first trunk page in the free-list.
- */
- if ( pPage == null && SQLITE_OK != ( rc = btreeGetPage( pBt, iPage, ref pPage, 0 ) ) )
- {
- goto freepage_out;
- }
- rc = sqlite3PagerWrite( pPage.pDbPage );
- if ( rc != SQLITE_OK )
- {
- goto freepage_out;
- }
- sqlite3Put4byte( pPage.aData, iTrunk );
- sqlite3Put4byte( pPage.aData, 4, 0 );
- sqlite3Put4byte( pPage1.aData, (u32)32, iPage );
- TRACE( "FREE-PAGE: %d new trunk page replacing %d\n", pPage.pgno, iTrunk );
-
-freepage_out:
- if ( pPage != null )
- {
- pPage.isInit = 0;
- }
- releasePage( pPage );
- releasePage( pTrunk );
- return rc;
-}
-static void freePage( MemPage pPage, ref int pRC )
-{
- if ( ( pRC ) == SQLITE_OK )
- {
- pRC = freePage2( pPage.pBt, pPage, pPage.pgno );
- }
-}
+ /* Now manipulate the actual database free-list structure. There are two
+ ** possibilities. If the free-list is currently empty, or if the first
+ ** trunk page in the free-list is full, then this page will become a
+ ** new free-list trunk page. Otherwise, it will become a leaf of the
+ ** first trunk page in the current free-list. This block tests if it
+ ** is possible to add the page as a new free-list leaf.
+ */
+ if (nFree != 0) {
+ u32 nLeaf; /* Initial number of leaf cells on trunk page */
+
+ iTrunk = sqlite3Get4byte(pPage1.aData, 32);
+ rc = btreeGetPage(pBt, iTrunk, ref pTrunk, 0);
+ if (rc != SQLITE_OK) {
+ goto freepage_out;
+ }
+
+ nLeaf = sqlite3Get4byte(pTrunk.aData, 4);
+ Debug.Assert(pBt.usableSize > 32);
+ if (nLeaf > (u32)pBt.usableSize / 4 - 2) {
+ rc = SQLITE_CORRUPT_BKPT();
+ goto freepage_out;
+ }
+ if (nLeaf < (u32)pBt.usableSize / 4 - 8) {
+ /* In this case there is room on the trunk page to insert the page
+ ** being freed as a new leaf.
+ **
+ ** Note that the trunk page is not really full until it contains
+ ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
+ ** coded. But due to a coding error in versions of SQLite prior to
+ ** 3.6.0, databases with freelist trunk pages holding more than
+ ** usableSize/4 - 8 entries will be reported as corrupt. In order
+ ** to maintain backwards compatibility with older versions of SQLite,
+ ** we will continue to restrict the number of entries to usableSize/4 - 8
+ ** for now. At some point in the future (once everyone has upgraded
+ ** to 3.6.0 or later) we should consider fixing the conditional above
+ ** to read "usableSize/4-2" instead of "usableSize/4-8".
+ */
+ rc = sqlite3PagerWrite(pTrunk.pDbPage);
+ if (rc == SQLITE_OK) {
+ sqlite3Put4byte(pTrunk.aData, (u32)4, nLeaf + 1);
+ sqlite3Put4byte(pTrunk.aData, (u32)8 + nLeaf * 4, iPage);
+ if (pPage != null && !pBt.secureDelete) {
+ sqlite3PagerDontWrite(pPage.pDbPage);
+ }
+ rc = btreeSetHasContent(pBt, iPage);
+ }
+ TRACE("FREE-PAGE: %d leaf on trunk page %d\n", iPage, pTrunk.pgno);
+ goto freepage_out;
+ }
+ }
-/*
-** Free any overflow pages associated with the given Cell.
-*/
-static int clearCell( MemPage pPage, int pCell )
-{
- BtShared pBt = pPage.pBt;
- CellInfo info = new CellInfo();
- Pgno ovflPgno;
- int rc;
- int nOvfl;
- u32 ovflPageSize;
-
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- btreeParseCellPtr( pPage, pCell, ref info );
- if ( info.iOverflow == 0 )
- {
- return SQLITE_OK; /* No overflow pages. Return without doing anything */
- }
- ovflPgno = sqlite3Get4byte( pPage.aData, pCell, info.iOverflow );
- Debug.Assert( pBt.usableSize > 4 );
- ovflPageSize = (u16)( pBt.usableSize - 4 );
- nOvfl = (int)( ( info.nPayload - info.nLocal + ovflPageSize - 1 ) / ovflPageSize );
- Debug.Assert( ovflPgno == 0 || nOvfl > 0 );
- while ( nOvfl-- != 0 )
- {
- Pgno iNext = 0;
- MemPage pOvfl = null;
- if ( ovflPgno < 2 || ovflPgno > btreePagecount( pBt ) )
- {
- /* 0 is not a legal page number and page 1 cannot be an
- ** overflow page. Therefore if ovflPgno<2 or past the end of the
- ** file the database must be corrupt. */
- return SQLITE_CORRUPT_BKPT();
- }
- if ( nOvfl != 0 )
- {
- rc = getOverflowPage( pBt, ovflPgno, out pOvfl, out iNext );
- if ( rc != 0 )
- return rc;
- }
+ /* If control flows to this point, then it was not possible to add the
+ ** the page being freed as a leaf page of the first trunk in the free-list.
+ ** Possibly because the free-list is empty, or possibly because the
+ ** first trunk in the free-list is full. Either way, the page being freed
+ ** will become the new first trunk page in the free-list.
+ */
+ if (pPage == null && SQLITE_OK != (rc = btreeGetPage(pBt, iPage, ref pPage, 0))) {
+ goto freepage_out;
+ }
+ rc = sqlite3PagerWrite(pPage.pDbPage);
+ if (rc != SQLITE_OK) {
+ goto freepage_out;
+ }
+ sqlite3Put4byte(pPage.aData, iTrunk);
+ sqlite3Put4byte(pPage.aData, 4, 0);
+ sqlite3Put4byte(pPage1.aData, (u32)32, iPage);
+ TRACE("FREE-PAGE: %d new trunk page replacing %d\n", pPage.pgno, iTrunk);
+
+ freepage_out:
+ if (pPage != null) {
+ pPage.isInit = 0;
+ }
+ releasePage(pPage);
+ releasePage(pTrunk);
+ return rc;
+ }
+ static void freePage(MemPage pPage, ref int pRC) {
+ if ((pRC) == SQLITE_OK) {
+ pRC = freePage2(pPage.pBt, pPage, pPage.pgno);
+ }
+ }
- if ( ( pOvfl != null || ( ( pOvfl = btreePageLookup( pBt, ovflPgno ) ) != null ) )
- && sqlite3PagerPageRefcount( pOvfl.pDbPage ) != 1
- )
- {
- /* There is no reason any cursor should have an outstanding reference
- ** to an overflow page belonging to a cell that is being deleted/updated.
- ** So if there exists more than one reference to this page, then it
- ** must not really be an overflow page and the database must be corrupt.
- ** It is helpful to detect this before calling freePage2(), as
- ** freePage2() may zero the page contents if secure-delete mode is
- ** enabled. If this 'overflow' page happens to be a page that the
- ** caller is iterating through or using in some other way, this
- ** can be problematic.
- */
- rc = SQLITE_CORRUPT_BKPT();
- }
- else
- {
- rc = freePage2( pBt, pOvfl, ovflPgno );
- }
- if ( pOvfl != null )
- {
- sqlite3PagerUnref( pOvfl.pDbPage );
- }
- if ( rc != 0 )
- return rc;
- ovflPgno = iNext;
- }
- return SQLITE_OK;
-}
+ /*
+ ** Free any overflow pages associated with the given Cell.
+ */
+ static int clearCell(MemPage pPage, int pCell) {
+ BtShared pBt = pPage.pBt;
+ CellInfo info = new CellInfo();
+ Pgno ovflPgno;
+ int rc;
+ int nOvfl;
+ u32 ovflPageSize;
+
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ btreeParseCellPtr(pPage, pCell, ref info);
+ if (info.iOverflow == 0) {
+ return SQLITE_OK; /* No overflow pages. Return without doing anything */
+ }
+ ovflPgno = sqlite3Get4byte(pPage.aData, pCell, info.iOverflow);
+ Debug.Assert(pBt.usableSize > 4);
+ ovflPageSize = (u16)(pBt.usableSize - 4);
+ nOvfl = (int)((info.nPayload - info.nLocal + ovflPageSize - 1) / ovflPageSize);
+ Debug.Assert(ovflPgno == 0 || nOvfl > 0);
+ while (nOvfl-- != 0) {
+ Pgno iNext = 0;
+ MemPage pOvfl = null;
+ if (ovflPgno < 2 || ovflPgno > btreePagecount(pBt)) {
+ /* 0 is not a legal page number and page 1 cannot be an
+ ** overflow page. Therefore if ovflPgno<2 or past the end of the
+ ** file the database must be corrupt. */
+ return SQLITE_CORRUPT_BKPT();
+ }
+ if (nOvfl != 0) {
+ rc = getOverflowPage(pBt, ovflPgno, out pOvfl, out iNext);
+ if (rc != 0)
+ return rc;
+ }
+
+ if ((pOvfl != null || ((pOvfl = btreePageLookup(pBt, ovflPgno)) != null))
+ && sqlite3PagerPageRefcount(pOvfl.pDbPage) != 1
+ ) {
+ /* There is no reason any cursor should have an outstanding reference
+ ** to an overflow page belonging to a cell that is being deleted/updated.
+ ** So if there exists more than one reference to this page, then it
+ ** must not really be an overflow page and the database must be corrupt.
+ ** It is helpful to detect this before calling freePage2(), as
+ ** freePage2() may zero the page contents if secure-delete mode is
+ ** enabled. If this 'overflow' page happens to be a page that the
+ ** caller is iterating through or using in some other way, this
+ ** can be problematic.
+ */
+ rc = SQLITE_CORRUPT_BKPT();
+ } else {
+ rc = freePage2(pBt, pOvfl, ovflPgno);
+ }
+ if (pOvfl != null) {
+ sqlite3PagerUnref(pOvfl.pDbPage);
+ }
+ if (rc != 0)
+ return rc;
+ ovflPgno = iNext;
+ }
+ return SQLITE_OK;
+ }
-/*
-** Create the byte sequence used to represent a cell on page pPage
-** and write that byte sequence into pCell[]. Overflow pages are
-** allocated and filled in as necessary. The calling procedure
-** is responsible for making sure sufficient space has been allocated
-** for pCell[].
-**
-** Note that pCell does not necessary need to point to the pPage.aData
-** area. pCell might point to some temporary storage. The cell will
-** be constructed in this temporary area then copied into pPage.aData
-** later.
-*/
-static int fillInCell(
-MemPage pPage, /* The page that contains the cell */
-byte[] pCell, /* Complete text of the cell */
-byte[] pKey, i64 nKey, /* The key */
-byte[] pData, int nData, /* The data */
-int nZero, /* Extra zero bytes to append to pData */
-ref int pnSize /* Write cell size here */
-)
-{
- int nPayload;
- u8[] pSrc;
- int pSrcIndex = 0;
- int nSrc, n, rc;
- int spaceLeft;
- MemPage pOvfl = null;
- MemPage pToRelease = null;
- byte[] pPrior;
- int pPriorIndex = 0;
- byte[] pPayload;
- int pPayloadIndex = 0;
- BtShared pBt = pPage.pBt;
- Pgno pgnoOvfl = 0;
- int nHeader;
- CellInfo info = new CellInfo();
-
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
-
- /* pPage is not necessarily writeable since pCell might be auxiliary
- ** buffer space that is separate from the pPage buffer area */
- // TODO -- Determine if the following Assert is needed under c#
- //Debug.Assert( pCell < pPage.aData || pCell >= &pPage.aData[pBt.pageSize]
- // || sqlite3PagerIswriteable(pPage.pDbPage) );
-
- /* Fill in the header. */
- nHeader = 0;
- if ( 0 == pPage.leaf )
- {
- nHeader += 4;
- }
- if ( pPage.hasData != 0 )
- {
- nHeader += (int)putVarint( pCell, nHeader, (int)( nData + nZero ) ); //putVarint( pCell[nHeader], nData + nZero );
- }
- else
- {
- nData = nZero = 0;
- }
- nHeader += putVarint( pCell, nHeader, (u64)nKey ); //putVarint( pCell[nHeader], *(u64*)&nKey );
- btreeParseCellPtr( pPage, pCell, ref info );
- Debug.Assert( info.nHeader == nHeader );
- Debug.Assert( info.nKey == nKey );
- Debug.Assert( info.nData == (u32)( nData + nZero ) );
-
- /* Fill in the payload */
- nPayload = nData + nZero;
- if ( pPage.intKey != 0 )
- {
- pSrc = pData;
- nSrc = nData;
- nData = 0;
- }
- else
- {
- if ( NEVER( nKey > 0x7fffffff || pKey == null ) )
- {
- return SQLITE_CORRUPT_BKPT();
- }
- nPayload += (int)nKey;
- pSrc = pKey;
- nSrc = (int)nKey;
- }
- pnSize = info.nSize;
- spaceLeft = info.nLocal;
- // pPayload = &pCell[nHeader];
- pPayload = pCell;
- pPayloadIndex = nHeader;
- // pPrior = &pCell[info.iOverflow];
- pPrior = pCell;
- pPriorIndex = info.iOverflow;
-
- while ( nPayload > 0 )
- {
- if ( spaceLeft == 0 )
- {
+ /*
+ ** Create the byte sequence used to represent a cell on page pPage
+ ** and write that byte sequence into pCell[]. Overflow pages are
+ ** allocated and filled in as necessary. The calling procedure
+ ** is responsible for making sure sufficient space has been allocated
+ ** for pCell[].
+ **
+ ** Note that pCell does not necessary need to point to the pPage.aData
+ ** area. pCell might point to some temporary storage. The cell will
+ ** be constructed in this temporary area then copied into pPage.aData
+ ** later.
+ */
+ static int fillInCell(
+ MemPage pPage, /* The page that contains the cell */
+ byte[] pCell, /* Complete text of the cell */
+ byte[] pKey, i64 nKey, /* The key */
+ byte[] pData, int nData, /* The data */
+ int nZero, /* Extra zero bytes to append to pData */
+ ref int pnSize /* Write cell size here */
+ ) {
+ int nPayload;
+ u8[] pSrc;
+ int pSrcIndex = 0;
+ int nSrc, n, rc;
+ int spaceLeft;
+ MemPage pOvfl = null;
+ MemPage pToRelease = null;
+ byte[] pPrior;
+ int pPriorIndex = 0;
+ byte[] pPayload;
+ int pPayloadIndex = 0;
+ BtShared pBt = pPage.pBt;
+ Pgno pgnoOvfl = 0;
+ int nHeader;
+ CellInfo info = new CellInfo();
+
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+
+ /* pPage is not necessarily writeable since pCell might be auxiliary
+ ** buffer space that is separate from the pPage buffer area */
+ // TODO -- Determine if the following Assert is needed under c#
+ //Debug.Assert( pCell < pPage.aData || pCell >= &pPage.aData[pBt.pageSize]
+ // || sqlite3PagerIswriteable(pPage.pDbPage) );
+
+ /* Fill in the header. */
+ nHeader = 0;
+ if (0 == pPage.leaf) {
+ nHeader += 4;
+ }
+ if (pPage.hasData != 0) {
+ nHeader += (int)putVarint(pCell, nHeader, (int)(nData + nZero)); //putVarint( pCell[nHeader], nData + nZero );
+ } else {
+ nData = nZero = 0;
+ }
+ nHeader += putVarint(pCell, nHeader, (u64)nKey); //putVarint( pCell[nHeader], *(u64*)&nKey );
+ btreeParseCellPtr(pPage, pCell, ref info);
+ Debug.Assert(info.nHeader == nHeader);
+ Debug.Assert(info.nKey == nKey);
+ Debug.Assert(info.nData == (u32)(nData + nZero));
+
+ /* Fill in the payload */
+ nPayload = nData + nZero;
+ if (pPage.intKey != 0) {
+ pSrc = pData;
+ nSrc = nData;
+ nData = 0;
+ } else {
+ if (NEVER(nKey > 0x7fffffff || pKey == null)) {
+ return SQLITE_CORRUPT_BKPT();
+ }
+ nPayload += (int)nKey;
+ pSrc = pKey;
+ nSrc = (int)nKey;
+ }
+ pnSize = info.nSize;
+ spaceLeft = info.nLocal;
+ // pPayload = &pCell[nHeader];
+ pPayload = pCell;
+ pPayloadIndex = nHeader;
+ // pPrior = &pCell[info.iOverflow];
+ pPrior = pCell;
+ pPriorIndex = info.iOverflow;
+
+ while (nPayload > 0) {
+ if (spaceLeft == 0) {
#if !SQLITE_OMIT_AUTOVACUUM
- Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
- if ( pBt.autoVacuum )
- {
- do
- {
- pgnoOvfl++;
- } while (
- PTRMAP_ISPAGE( pBt, pgnoOvfl ) || pgnoOvfl == PENDING_BYTE_PAGE( pBt )
- );
- }
+ Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
+ if (pBt.autoVacuum) {
+ do {
+ pgnoOvfl++;
+ } while (
+ PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl == PENDING_BYTE_PAGE(pBt)
+ );
+ }
#endif
- rc = allocateBtreePage( pBt, ref pOvfl, ref pgnoOvfl, pgnoOvfl, 0 );
+ rc = allocateBtreePage(pBt, ref pOvfl, ref pgnoOvfl, pgnoOvfl, 0);
#if !SQLITE_OMIT_AUTOVACUUM
- /* If the database supports auto-vacuum, and the second or subsequent
-** overflow page is being allocated, add an entry to the pointer-map
-** for that page now.
-**
-** If this is the first overflow page, then write a partial entry
-** to the pointer-map. If we write nothing to this pointer-map slot,
-** then the optimistic overflow chain processing in clearCell()
-** may misinterpret the uninitialised values and delete the
-** wrong pages from the database.
-*/
- if ( pBt.autoVacuum && rc == SQLITE_OK )
- {
- u8 eType = (u8)( pgnoPtrmap != 0 ? PTRMAP_OVERFLOW2 : PTRMAP_OVERFLOW1 );
- ptrmapPut( pBt, pgnoOvfl, eType, pgnoPtrmap, ref rc );
- if ( rc != 0 )
- {
- releasePage( pOvfl );
- }
- }
+ /* If the database supports auto-vacuum, and the second or subsequent
+ ** overflow page is being allocated, add an entry to the pointer-map
+ ** for that page now.
+ **
+ ** If this is the first overflow page, then write a partial entry
+ ** to the pointer-map. If we write nothing to this pointer-map slot,
+ ** then the optimistic overflow chain processing in clearCell()
+ ** may misinterpret the uninitialised values and delete the
+ ** wrong pages from the database.
+ */
+ if (pBt.autoVacuum && rc == SQLITE_OK) {
+ u8 eType = (u8)(pgnoPtrmap != 0 ? PTRMAP_OVERFLOW2 : PTRMAP_OVERFLOW1);
+ ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, ref rc);
+ if (rc != 0) {
+ releasePage(pOvfl);
+ }
+ }
#endif
- if ( rc != 0 )
- {
- releasePage( pToRelease );
- return rc;
- }
-
- /* If pToRelease is not zero than pPrior points into the data area
- ** of pToRelease. Make sure pToRelease is still writeable. */
- Debug.Assert( pToRelease == null || sqlite3PagerIswriteable( pToRelease.pDbPage ) );
-
- /* If pPrior is part of the data area of pPage, then make sure pPage
- ** is still writeable */
- // TODO -- Determine if the following Assert is needed under c#
- //Debug.Assert( pPrior < pPage.aData || pPrior >= &pPage.aData[pBt.pageSize]
- // || sqlite3PagerIswriteable(pPage.pDbPage) );
-
- sqlite3Put4byte( pPrior, pPriorIndex, pgnoOvfl );
- releasePage( pToRelease );
- pToRelease = pOvfl;
- pPrior = pOvfl.aData;
- pPriorIndex = 0;
- sqlite3Put4byte( pPrior, 0 );
- pPayload = pOvfl.aData;
- pPayloadIndex = 4; //&pOvfl.aData[4];
- spaceLeft = (int)pBt.usableSize - 4;
- }
- n = nPayload;
- if ( n > spaceLeft )
- n = spaceLeft;
-
- /* If pToRelease is not zero than pPayload points into the data area
- ** of pToRelease. Make sure pToRelease is still writeable. */
- Debug.Assert( pToRelease == null || sqlite3PagerIswriteable( pToRelease.pDbPage ) );
-
- /* If pPayload is part of the data area of pPage, then make sure pPage
- ** is still writeable */
- // TODO -- Determine if the following Assert is needed under c#
- //Debug.Assert( pPayload < pPage.aData || pPayload >= &pPage.aData[pBt.pageSize]
- // || sqlite3PagerIswriteable(pPage.pDbPage) );
-
- if ( nSrc > 0 )
- {
- if ( n > nSrc )
- n = nSrc;
- Debug.Assert( pSrc != null );
- Buffer.BlockCopy( pSrc, pSrcIndex, pPayload, pPayloadIndex, n );//memcpy(pPayload, pSrc, n);
- }
- else
- {
- byte[] pZeroBlob = sqlite3Malloc( n ); // memset(pPayload, 0, n);
- Buffer.BlockCopy( pZeroBlob, 0, pPayload, pPayloadIndex, n );
- }
- nPayload -= n;
- pPayloadIndex += n;// pPayload += n;
- pSrcIndex += n;// pSrc += n;
- nSrc -= n;
- spaceLeft -= n;
- if ( nSrc == 0 )
- {
- nSrc = nData;
- pSrc = pData;
- }
- }
- releasePage( pToRelease );
- return SQLITE_OK;
-}
-
-/*
-** Remove the i-th cell from pPage. This routine effects pPage only.
-** The cell content is not freed or deallocated. It is assumed that
-** the cell content has been copied someplace else. This routine just
-** removes the reference to the cell from pPage.
-**
-** "sz" must be the number of bytes in the cell.
-*/
-static void dropCell( MemPage pPage, int idx, int sz, ref int pRC )
-{
- u32 pc; /* Offset to cell content of cell being deleted */
- u8[] data; /* pPage.aData */
- int ptr; /* Used to move bytes around within data[] */
- int endPtr; /* End of loop */
- int rc; /* The return code */
- int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
-
- if ( pRC != 0 )
- return;
+ if (rc != 0) {
+ releasePage(pToRelease);
+ return rc;
+ }
+
+ /* If pToRelease is not zero than pPrior points into the data area
+ ** of pToRelease. Make sure pToRelease is still writeable. */
+ Debug.Assert(pToRelease == null || sqlite3PagerIswriteable(pToRelease.pDbPage));
+
+ /* If pPrior is part of the data area of pPage, then make sure pPage
+ ** is still writeable */
+ // TODO -- Determine if the following Assert is needed under c#
+ //Debug.Assert( pPrior < pPage.aData || pPrior >= &pPage.aData[pBt.pageSize]
+ // || sqlite3PagerIswriteable(pPage.pDbPage) );
+
+ sqlite3Put4byte(pPrior, pPriorIndex, pgnoOvfl);
+ releasePage(pToRelease);
+ pToRelease = pOvfl;
+ pPrior = pOvfl.aData;
+ pPriorIndex = 0;
+ sqlite3Put4byte(pPrior, 0);
+ pPayload = pOvfl.aData;
+ pPayloadIndex = 4; //&pOvfl.aData[4];
+ spaceLeft = (int)pBt.usableSize - 4;
+ }
+ n = nPayload;
+ if (n > spaceLeft)
+ n = spaceLeft;
+
+ /* If pToRelease is not zero than pPayload points into the data area
+ ** of pToRelease. Make sure pToRelease is still writeable. */
+ Debug.Assert(pToRelease == null || sqlite3PagerIswriteable(pToRelease.pDbPage));
+
+ /* If pPayload is part of the data area of pPage, then make sure pPage
+ ** is still writeable */
+ // TODO -- Determine if the following Assert is needed under c#
+ //Debug.Assert( pPayload < pPage.aData || pPayload >= &pPage.aData[pBt.pageSize]
+ // || sqlite3PagerIswriteable(pPage.pDbPage) );
+
+ if (nSrc > 0) {
+ if (n > nSrc)
+ n = nSrc;
+ Debug.Assert(pSrc != null);
+ Buffer.BlockCopy(pSrc, pSrcIndex, pPayload, pPayloadIndex, n);//memcpy(pPayload, pSrc, n);
+ } else {
+ byte[] pZeroBlob = sqlite3Malloc(n); // memset(pPayload, 0, n);
+ Buffer.BlockCopy(pZeroBlob, 0, pPayload, pPayloadIndex, n);
+ }
+ nPayload -= n;
+ pPayloadIndex += n;// pPayload += n;
+ pSrcIndex += n;// pSrc += n;
+ nSrc -= n;
+ spaceLeft -= n;
+ if (nSrc == 0) {
+ nSrc = nData;
+ pSrc = pData;
+ }
+ }
+ releasePage(pToRelease);
+ return SQLITE_OK;
+ }
- Debug.Assert( idx >= 0 && idx < pPage.nCell );
+ /*
+ ** Remove the i-th cell from pPage. This routine effects pPage only.
+ ** The cell content is not freed or deallocated. It is assumed that
+ ** the cell content has been copied someplace else. This routine just
+ ** removes the reference to the cell from pPage.
+ **
+ ** "sz" must be the number of bytes in the cell.
+ */
+ static void dropCell(MemPage pPage, int idx, int sz, ref int pRC) {
+ u32 pc; /* Offset to cell content of cell being deleted */
+ u8[] data; /* pPage.aData */
+ int ptr; /* Used to move bytes around within data[] */
+ int endPtr; /* End of loop */
+ int rc; /* The return code */
+ int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
+
+ if (pRC != 0)
+ return;
+
+ Debug.Assert(idx >= 0 && idx < pPage.nCell);
#if SQLITE_DEBUG
- Debug.Assert( sz == cellSize( pPage, idx ) );
+ Debug.Assert(sz == cellSize(pPage, idx));
#endif
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- data = pPage.aData;
- ptr = pPage.cellOffset + 2 * idx; //ptr = &data[pPage.cellOffset + 2 * idx];
- pc = (u32)get2byte( data, ptr );
- hdr = pPage.hdrOffset;
- testcase( pc == get2byte( data, hdr + 5 ) );
- testcase( pc + sz == pPage.pBt.usableSize );
- if ( pc < (u32)get2byte( data, hdr + 5 ) || pc + sz > pPage.pBt.usableSize )
- {
- pRC = SQLITE_CORRUPT_BKPT();
- return;
- }
- rc = freeSpace( pPage, pc, sz );
- if ( rc != 0 )
- {
- pRC = rc;
- return;
- }
- //endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
- //assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
- //while( ptr> 8 );
- data[pPage.hdrOffset + 4] = (byte)( pPage.nCell ); //put2byte( data, hdr + 3, pPage.nCell );
- pPage.nFree += 2;
-}
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ data = pPage.aData;
+ ptr = pPage.cellOffset + 2 * idx; //ptr = &data[pPage.cellOffset + 2 * idx];
+ pc = (u32)get2byte(data, ptr);
+ hdr = pPage.hdrOffset;
+ testcase(pc == get2byte(data, hdr + 5));
+ testcase(pc + sz == pPage.pBt.usableSize);
+ if (pc < (u32)get2byte(data, hdr + 5) || pc + sz > pPage.pBt.usableSize) {
+ pRC = SQLITE_CORRUPT_BKPT();
+ return;
+ }
+ rc = freeSpace(pPage, pc, sz);
+ if (rc != 0) {
+ pRC = rc;
+ return;
+ }
+ //endPtr = &data[pPage->cellOffset + 2*pPage->nCell - 2];
+ //assert( (SQLITE_PTR_TO_INT(ptr)&1)==0 ); /* ptr is always 2-byte aligned */
+ //while( ptr> 8);
+ data[pPage.hdrOffset + 4] = (byte)(pPage.nCell); //put2byte( data, hdr + 3, pPage.nCell );
+ pPage.nFree += 2;
+ }
-/*
-** Insert a new cell on pPage at cell index "i". pCell points to the
-** content of the cell.
-**
-** If the cell content will fit on the page, then put it there. If it
-** will not fit, then make a copy of the cell content into pTemp if
-** pTemp is not null. Regardless of pTemp, allocate a new entry
-** in pPage.aOvfl[] and make it point to the cell content (either
-** in pTemp or the original pCell) and also record its index.
-** Allocating a new entry in pPage.aCell[] implies that
-** pPage.nOverflow is incremented.
-**
-** If nSkip is non-zero, then do not copy the first nSkip bytes of the
-** cell. The caller will overwrite them after this function returns. If
-** nSkip is non-zero, then pCell may not point to an invalid memory location
-** (but pCell+nSkip is always valid).
-*/
-static void insertCell(
-MemPage pPage, /* Page into which we are copying */
-int i, /* New cell becomes the i-th cell of the page */
-u8[] pCell, /* Content of the new cell */
-int sz, /* Bytes of content in pCell */
-u8[] pTemp, /* Temp storage space for pCell, if needed */
-Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
-ref int pRC /* Read and write return code from here */
-)
-{
- int idx = 0; /* Where to write new cell content in data[] */
- int j; /* Loop counter */
- int end; /* First byte past the last cell pointer in data[] */
- int ins; /* Index in data[] where new cell pointer is inserted */
- int cellOffset; /* Address of first cell pointer in data[] */
- u8[] data; /* The content of the whole page */
- u8 ptr; /* Used for moving information around in data[] */
- u8 endPtr; /* End of the loop */
-
- int nSkip = ( iChild != 0 ? 4 : 0 );
-
- if ( pRC != 0 )
- return;
-
- Debug.Assert( i >= 0 && i <= pPage.nCell + pPage.nOverflow );
- Debug.Assert( pPage.nCell <= MX_CELL( pPage.pBt ) && MX_CELL( pPage.pBt ) <= 10921 );
- Debug.Assert( pPage.nOverflow <= ArraySize( pPage.aOvfl ) );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- /* The cell should normally be sized correctly. However, when moving a
- ** malformed cell from a leaf page to an interior page, if the cell size
- ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
- ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
- ** the term after the || in the following assert(). */
- Debug.Assert( sz == cellSizePtr( pPage, pCell ) || ( sz == 8 && iChild > 0 ) );
- if ( pPage.nOverflow != 0 || sz + 2 > pPage.nFree )
- {
- if ( pTemp != null )
- {
- Buffer.BlockCopy( pCell, nSkip, pTemp, nSkip, sz - nSkip );//memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
- pCell = pTemp;
- }
- if ( iChild != 0 )
- {
- sqlite3Put4byte( pCell, iChild );
- }
- j = pPage.nOverflow++;
- Debug.Assert( j < pPage.aOvfl.Length );//(int)(sizeof(pPage.aOvfl)/sizeof(pPage.aOvfl[0])) );
- pPage.aOvfl[j].pCell = pCell;
- pPage.aOvfl[j].idx = (u16)i;
- }
- else
- {
- int rc = sqlite3PagerWrite( pPage.pDbPage );
- if ( rc != SQLITE_OK )
- {
- pRC = rc;
- return;
- }
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
- data = pPage.aData;
- cellOffset = pPage.cellOffset;
- end = cellOffset + 2 * pPage.nCell;
- ins = cellOffset + 2 * i;
- rc = allocateSpace( pPage, sz, ref idx );
- if ( rc != 0 )
- {
- pRC = rc;
- return;
- }
- /* The allocateSpace() routine guarantees the following two properties
- ** if it returns success */
- Debug.Assert( idx >= end + 2 );
- Debug.Assert( idx + sz <= (int)pPage.pBt.usableSize );
- pPage.nCell++;
- pPage.nFree -= (u16)( 2 + sz );
- Buffer.BlockCopy( pCell, nSkip, data, idx + nSkip, sz - nSkip ); //memcpy( data[idx + nSkip], pCell + nSkip, sz - nSkip );
- if ( iChild != 0 )
- {
- sqlite3Put4byte( data, idx, iChild );
- }
- //ptr = &data[end];
- //endPtr = &data[ins];
- //assert( ( SQLITE_PTR_TO_INT( ptr ) & 1 ) == 0 ); /* ptr is always 2-byte aligned */
- //while ( ptr > endPtr )
- //{
- // *(u16*)ptr = *(u16*)&ptr[-2];
- // ptr -= 2;
- //}
- for ( j = end; j > ins; j -= 2 )
- {
- data[j + 0] = data[j - 2];
- data[j + 1] = data[j - 1];
- }
- put2byte( data, ins, idx );
- put2byte( data, pPage.hdrOffset + 3, pPage.nCell );
+ /*
+ ** Insert a new cell on pPage at cell index "i". pCell points to the
+ ** content of the cell.
+ **
+ ** If the cell content will fit on the page, then put it there. If it
+ ** will not fit, then make a copy of the cell content into pTemp if
+ ** pTemp is not null. Regardless of pTemp, allocate a new entry
+ ** in pPage.aOvfl[] and make it point to the cell content (either
+ ** in pTemp or the original pCell) and also record its index.
+ ** Allocating a new entry in pPage.aCell[] implies that
+ ** pPage.nOverflow is incremented.
+ **
+ ** If nSkip is non-zero, then do not copy the first nSkip bytes of the
+ ** cell. The caller will overwrite them after this function returns. If
+ ** nSkip is non-zero, then pCell may not point to an invalid memory location
+ ** (but pCell+nSkip is always valid).
+ */
+ static void insertCell(
+ MemPage pPage, /* Page into which we are copying */
+ int i, /* New cell becomes the i-th cell of the page */
+ u8[] pCell, /* Content of the new cell */
+ int sz, /* Bytes of content in pCell */
+ u8[] pTemp, /* Temp storage space for pCell, if needed */
+ Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
+ ref int pRC /* Read and write return code from here */
+ ) {
+ int idx = 0; /* Where to write new cell content in data[] */
+ int j; /* Loop counter */
+ int end; /* First byte past the last cell pointer in data[] */
+ int ins; /* Index in data[] where new cell pointer is inserted */
+ int cellOffset; /* Address of first cell pointer in data[] */
+ u8[] data; /* The content of the whole page */
+ u8 ptr; /* Used for moving information around in data[] */
+ u8 endPtr; /* End of the loop */
+
+ int nSkip = (iChild != 0 ? 4 : 0);
+
+ if (pRC != 0)
+ return;
+
+ Debug.Assert(i >= 0 && i <= pPage.nCell + pPage.nOverflow);
+ Debug.Assert(pPage.nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 10921);
+ Debug.Assert(pPage.nOverflow <= ArraySize(pPage.aOvfl));
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ /* The cell should normally be sized correctly. However, when moving a
+ ** malformed cell from a leaf page to an interior page, if the cell size
+ ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
+ ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
+ ** the term after the || in the following assert(). */
+ Debug.Assert(sz == cellSizePtr(pPage, pCell) || (sz == 8 && iChild > 0));
+ if (pPage.nOverflow != 0 || sz + 2 > pPage.nFree) {
+ if (pTemp != null) {
+ Buffer.BlockCopy(pCell, nSkip, pTemp, nSkip, sz - nSkip);//memcpy(pTemp+nSkip, pCell+nSkip, sz-nSkip);
+ pCell = pTemp;
+ }
+ if (iChild != 0) {
+ sqlite3Put4byte(pCell, iChild);
+ }
+ j = pPage.nOverflow++;
+ Debug.Assert(j < pPage.aOvfl.Length);//(int)(sizeof(pPage.aOvfl)/sizeof(pPage.aOvfl[0])) );
+ pPage.aOvfl[j].pCell = pCell;
+ pPage.aOvfl[j].idx = (u16)i;
+ } else {
+ int rc = sqlite3PagerWrite(pPage.pDbPage);
+ if (rc != SQLITE_OK) {
+ pRC = rc;
+ return;
+ }
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+ data = pPage.aData;
+ cellOffset = pPage.cellOffset;
+ end = cellOffset + 2 * pPage.nCell;
+ ins = cellOffset + 2 * i;
+ rc = allocateSpace(pPage, sz, ref idx);
+ if (rc != 0) {
+ pRC = rc;
+ return;
+ }
+ /* The allocateSpace() routine guarantees the following two properties
+ ** if it returns success */
+ Debug.Assert(idx >= end + 2);
+ Debug.Assert(idx + sz <= (int)pPage.pBt.usableSize);
+ pPage.nCell++;
+ pPage.nFree -= (u16)(2 + sz);
+ Buffer.BlockCopy(pCell, nSkip, data, idx + nSkip, sz - nSkip); //memcpy( data[idx + nSkip], pCell + nSkip, sz - nSkip );
+ if (iChild != 0) {
+ sqlite3Put4byte(data, idx, iChild);
+ }
+ //ptr = &data[end];
+ //endPtr = &data[ins];
+ //assert( ( SQLITE_PTR_TO_INT( ptr ) & 1 ) == 0 ); /* ptr is always 2-byte aligned */
+ //while ( ptr > endPtr )
+ //{
+ // *(u16*)ptr = *(u16*)&ptr[-2];
+ // ptr -= 2;
+ //}
+ for (j = end; j > ins; j -= 2) {
+ data[j + 0] = data[j - 2];
+ data[j + 1] = data[j - 1];
+ }
+ put2byte(data, ins, idx);
+ put2byte(data, pPage.hdrOffset + 3, pPage.nCell);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pPage.pBt.autoVacuum )
- {
- /* The cell may contain a pointer to an overflow page. If so, write
- ** the entry for the overflow page into the pointer map.
- */
- ptrmapPutOvflPtr( pPage, pCell, ref pRC );
- }
+ if (pPage.pBt.autoVacuum) {
+ /* The cell may contain a pointer to an overflow page. If so, write
+ ** the entry for the overflow page into the pointer map.
+ */
+ ptrmapPutOvflPtr(pPage, pCell, ref pRC);
+ }
#endif
- }
-}
+ }
+ }
-/*
-** Add a list of cells to a page. The page should be initially empty.
-** The cells are guaranteed to fit on the page.
-*/
-static void assemblePage(
-MemPage pPage, /* The page to be assemblied */
-int nCell, /* The number of cells to add to this page */
-u8[] apCell, /* Pointer to a single the cell bodies */
-int[] aSize /* Sizes of the cells bodie*/
-)
-{
- int i; /* Loop counter */
- int pCellptr; /* Address of next cell pointer */
- int cellbody; /* Address of next cell body */
- byte[] data = pPage.aData; /* Pointer to data for pPage */
- int hdr = pPage.hdrOffset; /* Offset of header on pPage */
- int nUsable = (int)pPage.pBt.usableSize; /* Usable size of page */
-
- Debug.Assert( pPage.nOverflow == 0 );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( nCell >= 0 && nCell <= (int)MX_CELL( pPage.pBt )
- && (int)MX_CELL( pPage.pBt ) <= 10921 );
-
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
-
- /* Check that the page has just been zeroed by zeroPage() */
- Debug.Assert( pPage.nCell == 0 );
- Debug.Assert( get2byteNotZero( data, hdr + 5 ) == nUsable );
-
- pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2];
- cellbody = nUsable;
- for ( i = nCell - 1; i >= 0; i-- )
- {
- u16 sz = (u16)aSize[i];
- pCellptr -= 2;
- cellbody -= sz;
- put2byte( data, pCellptr, cellbody );
- Buffer.BlockCopy( apCell, 0, data, cellbody, sz );// memcpy(&data[cellbody], apCell[i], sz);
- }
- put2byte( data, hdr + 3, nCell );
- put2byte( data, hdr + 5, cellbody );
- pPage.nFree -= (u16)( nCell * 2 + nUsable - cellbody );
- pPage.nCell = (u16)nCell;
-}
-static void assemblePage(
-MemPage pPage, /* The page to be assemblied */
-int nCell, /* The number of cells to add to this page */
-u8[][] apCell, /* Pointers to cell bodies */
-u16[] aSize, /* Sizes of the cells */
-int offset /* Offset into the cell bodies, for c# */
-)
-{
- int i; /* Loop counter */
- int pCellptr; /* Address of next cell pointer */
- int cellbody; /* Address of next cell body */
- byte[] data = pPage.aData; /* Pointer to data for pPage */
- int hdr = pPage.hdrOffset; /* Offset of header on pPage */
- int nUsable = (int)pPage.pBt.usableSize; /* Usable size of page */
-
- Debug.Assert( pPage.nOverflow == 0 );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( nCell >= 0 && nCell <= MX_CELL( pPage.pBt ) && MX_CELL( pPage.pBt ) <= 5460 );
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
-
- /* Check that the page has just been zeroed by zeroPage() */
- Debug.Assert( pPage.nCell == 0 );
- Debug.Assert( get2byte( data, hdr + 5 ) == nUsable );
-
- pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2];
- cellbody = nUsable;
- for ( i = nCell - 1; i >= 0; i-- )
- {
- pCellptr -= 2;
- cellbody -= aSize[i + offset];
- put2byte( data, pCellptr, cellbody );
- Buffer.BlockCopy( apCell[offset + i], 0, data, cellbody, aSize[i + offset] );// memcpy(&data[cellbody], apCell[i], aSize[i]);
- }
- put2byte( data, hdr + 3, nCell );
- put2byte( data, hdr + 5, cellbody );
- pPage.nFree -= (u16)( nCell * 2 + nUsable - cellbody );
- pPage.nCell = (u16)nCell;
-}
+ /*
+ ** Add a list of cells to a page. The page should be initially empty.
+ ** The cells are guaranteed to fit on the page.
+ */
+ static void assemblePage(
+ MemPage pPage, /* The page to be assemblied */
+ int nCell, /* The number of cells to add to this page */
+ u8[] apCell, /* Pointer to a single the cell bodies */
+ int[] aSize /* Sizes of the cells bodie*/
+ ) {
+ int i; /* Loop counter */
+ int pCellptr; /* Address of next cell pointer */
+ int cellbody; /* Address of next cell body */
+ byte[] data = pPage.aData; /* Pointer to data for pPage */
+ int hdr = pPage.hdrOffset; /* Offset of header on pPage */
+ int nUsable = (int)pPage.pBt.usableSize; /* Usable size of page */
+
+ Debug.Assert(pPage.nOverflow == 0);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(nCell >= 0 && nCell <= (int)MX_CELL(pPage.pBt)
+ && (int)MX_CELL(pPage.pBt) <= 10921);
+
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+
+ /* Check that the page has just been zeroed by zeroPage() */
+ Debug.Assert(pPage.nCell == 0);
+ Debug.Assert(get2byteNotZero(data, hdr + 5) == nUsable);
+
+ pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2];
+ cellbody = nUsable;
+ for (i = nCell - 1; i >= 0; i--) {
+ u16 sz = (u16)aSize[i];
+ pCellptr -= 2;
+ cellbody -= sz;
+ put2byte(data, pCellptr, cellbody);
+ Buffer.BlockCopy(apCell, 0, data, cellbody, sz);// memcpy(&data[cellbody], apCell[i], sz);
+ }
+ put2byte(data, hdr + 3, nCell);
+ put2byte(data, hdr + 5, cellbody);
+ pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody);
+ pPage.nCell = (u16)nCell;
+ }
+ static void assemblePage(
+ MemPage pPage, /* The page to be assemblied */
+ int nCell, /* The number of cells to add to this page */
+ u8[][] apCell, /* Pointers to cell bodies */
+ u16[] aSize, /* Sizes of the cells */
+ int offset /* Offset into the cell bodies, for c# */
+ ) {
+ int i; /* Loop counter */
+ int pCellptr; /* Address of next cell pointer */
+ int cellbody; /* Address of next cell body */
+ byte[] data = pPage.aData; /* Pointer to data for pPage */
+ int hdr = pPage.hdrOffset; /* Offset of header on pPage */
+ int nUsable = (int)pPage.pBt.usableSize; /* Usable size of page */
+
+ Debug.Assert(pPage.nOverflow == 0);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460);
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+
+ /* Check that the page has just been zeroed by zeroPage() */
+ Debug.Assert(pPage.nCell == 0);
+ Debug.Assert(get2byte(data, hdr + 5) == nUsable);
+
+ pCellptr = pPage.cellOffset + nCell * 2; //data[pPage.cellOffset + nCell * 2];
+ cellbody = nUsable;
+ for (i = nCell - 1; i >= 0; i--) {
+ pCellptr -= 2;
+ cellbody -= aSize[i + offset];
+ put2byte(data, pCellptr, cellbody);
+ Buffer.BlockCopy(apCell[offset + i], 0, data, cellbody, aSize[i + offset]);// memcpy(&data[cellbody], apCell[i], aSize[i]);
+ }
+ put2byte(data, hdr + 3, nCell);
+ put2byte(data, hdr + 5, cellbody);
+ pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody);
+ pPage.nCell = (u16)nCell;
+ }
-static void assemblePage(
-MemPage pPage, /* The page to be assemblied */
-int nCell, /* The number of cells to add to this page */
-u8[] apCell, /* Pointers to cell bodies */
-u16[] aSize /* Sizes of the cells */
-)
-{
- int i; /* Loop counter */
- int pCellptr; /* Address of next cell pointer */
- int cellbody; /* Address of next cell body */
- u8[] data = pPage.aData; /* Pointer to data for pPage */
- int hdr = pPage.hdrOffset; /* Offset of header on pPage */
- int nUsable = (int)pPage.pBt.usableSize; /* Usable size of page */
-
- Debug.Assert( pPage.nOverflow == 0 );
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( nCell >= 0 && nCell <= MX_CELL( pPage.pBt ) && MX_CELL( pPage.pBt ) <= 5460 );
- Debug.Assert( sqlite3PagerIswriteable( pPage.pDbPage ) );
-
- /* Check that the page has just been zeroed by zeroPage() */
- Debug.Assert( pPage.nCell == 0 );
- Debug.Assert( get2byte( data, hdr + 5 ) == nUsable );
-
- pCellptr = pPage.cellOffset + nCell * 2; //&data[pPage.cellOffset + nCell * 2];
- cellbody = nUsable;
- for ( i = nCell - 1; i >= 0; i-- )
- {
- pCellptr -= 2;
- cellbody -= aSize[i];
- put2byte( data, pCellptr, cellbody );
- Buffer.BlockCopy( apCell, 0, data, cellbody, aSize[i] );//memcpy( data[cellbody], apCell[i], aSize[i] );
- }
- put2byte( data, hdr + 3, nCell );
- put2byte( data, hdr + 5, cellbody );
- pPage.nFree -= (u16)( nCell * 2 + nUsable - cellbody );
- pPage.nCell = (u16)nCell;
-}
+ static void assemblePage(
+ MemPage pPage, /* The page to be assemblied */
+ int nCell, /* The number of cells to add to this page */
+ u8[] apCell, /* Pointers to cell bodies */
+ u16[] aSize /* Sizes of the cells */
+ ) {
+ int i; /* Loop counter */
+ int pCellptr; /* Address of next cell pointer */
+ int cellbody; /* Address of next cell body */
+ u8[] data = pPage.aData; /* Pointer to data for pPage */
+ int hdr = pPage.hdrOffset; /* Offset of header on pPage */
+ int nUsable = (int)pPage.pBt.usableSize; /* Usable size of page */
+
+ Debug.Assert(pPage.nOverflow == 0);
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(nCell >= 0 && nCell <= MX_CELL(pPage.pBt) && MX_CELL(pPage.pBt) <= 5460);
+ Debug.Assert(sqlite3PagerIswriteable(pPage.pDbPage));
+
+ /* Check that the page has just been zeroed by zeroPage() */
+ Debug.Assert(pPage.nCell == 0);
+ Debug.Assert(get2byte(data, hdr + 5) == nUsable);
+
+ pCellptr = pPage.cellOffset + nCell * 2; //&data[pPage.cellOffset + nCell * 2];
+ cellbody = nUsable;
+ for (i = nCell - 1; i >= 0; i--) {
+ pCellptr -= 2;
+ cellbody -= aSize[i];
+ put2byte(data, pCellptr, cellbody);
+ Buffer.BlockCopy(apCell, 0, data, cellbody, aSize[i]);//memcpy( data[cellbody], apCell[i], aSize[i] );
+ }
+ put2byte(data, hdr + 3, nCell);
+ put2byte(data, hdr + 5, cellbody);
+ pPage.nFree -= (u16)(nCell * 2 + nUsable - cellbody);
+ pPage.nCell = (u16)nCell;
+ }
-/*
-** The following parameters determine how many adjacent pages get involved
-** in a balancing operation. NN is the number of neighbors on either side
-** of the page that participate in the balancing operation. NB is the
-** total number of pages that participate, including the target page and
-** NN neighbors on either side.
-**
-** The minimum value of NN is 1 (of course). Increasing NN above 1
-** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
-** in exchange for a larger degradation in INSERT and UPDATE performance.
-** The value of NN appears to give the best results overall.
-*/
-static int NN = 1; /* Number of neighbors on either side of pPage */
-static int NB = ( NN * 2 + 1 ); /* Total pages involved in the balance */
+ /*
+ ** The following parameters determine how many adjacent pages get involved
+ ** in a balancing operation. NN is the number of neighbors on either side
+ ** of the page that participate in the balancing operation. NB is the
+ ** total number of pages that participate, including the target page and
+ ** NN neighbors on either side.
+ **
+ ** The minimum value of NN is 1 (of course). Increasing NN above 1
+ ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
+ ** in exchange for a larger degradation in INSERT and UPDATE performance.
+ ** The value of NN appears to give the best results overall.
+ */
+ static int NN = 1; /* Number of neighbors on either side of pPage */
+ static int NB = (NN * 2 + 1); /* Total pages involved in the balance */
#if !SQLITE_OMIT_QUICKBALANCE
-/*
-** This version of balance() handles the common special case where
-** a new entry is being inserted on the extreme right-end of the
-** tree, in other words, when the new entry will become the largest
-** entry in the tree.
-**
-** Instead of trying to balance the 3 right-most leaf pages, just add
-** a new page to the right-hand side and put the one new entry in
-** that page. This leaves the right side of the tree somewhat
-** unbalanced. But odds are that we will be inserting new entries
-** at the end soon afterwards so the nearly empty page will quickly
-** fill up. On average.
-**
-** pPage is the leaf page which is the right-most page in the tree.
-** pParent is its parent. pPage must have a single overflow entry
-** which is also the right-most entry on the page.
-**
-** The pSpace buffer is used to store a temporary copy of the divider
-** cell that will be inserted into pParent. Such a cell consists of a 4
-** byte page number followed by a variable length integer. In other
-** words, at most 13 bytes. Hence the pSpace buffer must be at
-** least 13 bytes in size.
-*/
-static int balance_quick( MemPage pParent, MemPage pPage, u8[] pSpace )
-{
- BtShared pBt = pPage.pBt; /* B-Tree Database */
- MemPage pNew = new MemPage();/* Newly allocated page */
- int rc; /* Return Code */
- Pgno pgnoNew = 0; /* Page number of pNew */
-
- Debug.Assert( sqlite3_mutex_held( pPage.pBt.mutex ) );
- Debug.Assert( sqlite3PagerIswriteable( pParent.pDbPage ) );
- Debug.Assert( pPage.nOverflow == 1 );
-
- /* This error condition is now caught prior to reaching this function */
- if ( pPage.nCell <= 0 )
- return SQLITE_CORRUPT_BKPT();
-
- /* Allocate a new page. This page will become the right-sibling of
- ** pPage. Make the parent page writable, so that the new divider cell
- ** may be inserted. If both these operations are successful, proceed.
- */
- rc = allocateBtreePage( pBt, ref pNew, ref pgnoNew, 0, 0 );
-
- if ( rc == SQLITE_OK )
- {
-
- int pOut = 4;//u8 pOut = &pSpace[4];
- u8[] pCell = pPage.aOvfl[0].pCell;
- int[] szCell = new int[1];
- szCell[0] = cellSizePtr( pPage, pCell );
- int pStop;
-
- Debug.Assert( sqlite3PagerIswriteable( pNew.pDbPage ) );
- Debug.Assert( pPage.aData[0] == ( PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF ) );
- zeroPage( pNew, PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF );
- assemblePage( pNew, 1, pCell, szCell );
-
- /* If this is an auto-vacuum database, update the pointer map
- ** with entries for the new page, and any pointer from the
- ** cell on the page to an overflow page. If either of these
- ** operations fails, the return code is set, but the contents
- ** of the parent page are still manipulated by thh code below.
- ** That is Ok, at this point the parent page is guaranteed to
- ** be marked as dirty. Returning an error code will cause a
- ** rollback, undoing any changes made to the parent page.
- */
+ /*
+ ** This version of balance() handles the common special case where
+ ** a new entry is being inserted on the extreme right-end of the
+ ** tree, in other words, when the new entry will become the largest
+ ** entry in the tree.
+ **
+ ** Instead of trying to balance the 3 right-most leaf pages, just add
+ ** a new page to the right-hand side and put the one new entry in
+ ** that page. This leaves the right side of the tree somewhat
+ ** unbalanced. But odds are that we will be inserting new entries
+ ** at the end soon afterwards so the nearly empty page will quickly
+ ** fill up. On average.
+ **
+ ** pPage is the leaf page which is the right-most page in the tree.
+ ** pParent is its parent. pPage must have a single overflow entry
+ ** which is also the right-most entry on the page.
+ **
+ ** The pSpace buffer is used to store a temporary copy of the divider
+ ** cell that will be inserted into pParent. Such a cell consists of a 4
+ ** byte page number followed by a variable length integer. In other
+ ** words, at most 13 bytes. Hence the pSpace buffer must be at
+ ** least 13 bytes in size.
+ */
+ static int balance_quick(MemPage pParent, MemPage pPage, u8[] pSpace) {
+ BtShared pBt = pPage.pBt; /* B-Tree Database */
+ MemPage pNew = new MemPage();/* Newly allocated page */
+ int rc; /* Return Code */
+ Pgno pgnoNew = 0; /* Page number of pNew */
+
+ Debug.Assert(sqlite3_mutex_held(pPage.pBt.mutex));
+ Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage));
+ Debug.Assert(pPage.nOverflow == 1);
+
+ /* This error condition is now caught prior to reaching this function */
+ if (pPage.nCell <= 0)
+ return SQLITE_CORRUPT_BKPT();
+
+ /* Allocate a new page. This page will become the right-sibling of
+ ** pPage. Make the parent page writable, so that the new divider cell
+ ** may be inserted. If both these operations are successful, proceed.
+ */
+ rc = allocateBtreePage(pBt, ref pNew, ref pgnoNew, 0, 0);
+
+ if (rc == SQLITE_OK) {
+
+ int pOut = 4;//u8 pOut = &pSpace[4];
+ u8[] pCell = pPage.aOvfl[0].pCell;
+ int[] szCell = new int[1];
+ szCell[0] = cellSizePtr(pPage, pCell);
+ int pStop;
+
+ Debug.Assert(sqlite3PagerIswriteable(pNew.pDbPage));
+ Debug.Assert(pPage.aData[0] == (PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF));
+ zeroPage(pNew, PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF);
+ assemblePage(pNew, 1, pCell, szCell);
+
+ /* If this is an auto-vacuum database, update the pointer map
+ ** with entries for the new page, and any pointer from the
+ ** cell on the page to an overflow page. If either of these
+ ** operations fails, the return code is set, but the contents
+ ** of the parent page are still manipulated by thh code below.
+ ** That is Ok, at this point the parent page is guaranteed to
+ ** be marked as dirty. Returning an error code will cause a
+ ** rollback, undoing any changes made to the parent page.
+ */
#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM )
- if ( pBt.autoVacuum )
+ if (pBt.autoVacuum)
#else
if (false)
#endif
- {
- ptrmapPut( pBt, pgnoNew, PTRMAP_BTREE, pParent.pgno, ref rc );
- if ( szCell[0] > pNew.minLocal )
- {
- ptrmapPutOvflPtr( pNew, pCell, ref rc );
- }
- }
+ {
+ ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent.pgno, ref rc);
+ if (szCell[0] > pNew.minLocal) {
+ ptrmapPutOvflPtr(pNew, pCell, ref rc);
+ }
+ }
+
+ /* Create a divider cell to insert into pParent. The divider cell
+ ** consists of a 4-byte page number (the page number of pPage) and
+ ** a variable length key value (which must be the same value as the
+ ** largest key on pPage).
+ **
+ ** To find the largest key value on pPage, first find the right-most
+ ** cell on pPage. The first two fields of this cell are the
+ ** record-length (a variable length integer at most 32-bits in size)
+ ** and the key value (a variable length integer, may have any value).
+ ** The first of the while(...) loops below skips over the record-length
+ ** field. The second while(...) loop copies the key value from the
+ ** cell on pPage into the pSpace buffer.
+ */
+ int iCell = findCell(pPage, pPage.nCell - 1); //pCell = findCell( pPage, pPage.nCell - 1 );
+ pCell = pPage.aData;
+ int _pCell = iCell;
+ pStop = _pCell + 9; //pStop = &pCell[9];
+ while (((pCell[_pCell++]) & 0x80) != 0 && _pCell < pStop)
+ ; //while ( ( *( pCell++ ) & 0x80 ) && pCell < pStop ) ;
+ pStop = _pCell + 9;//pStop = &pCell[9];
+ while (((pSpace[pOut++] = pCell[_pCell++]) & 0x80) != 0 && _pCell < pStop)
+ ; //while ( ( ( *( pOut++ ) = *( pCell++ ) ) & 0x80 ) && pCell < pStop ) ;
+
+ /* Insert the new divider cell into pParent. */
+ insertCell(pParent, pParent.nCell, pSpace, pOut, //(int)(pOut-pSpace),
+ null, pPage.pgno, ref rc);
+
+ /* Set the right-child pointer of pParent to point to the new page. */
+ sqlite3Put4byte(pParent.aData, pParent.hdrOffset + 8, pgnoNew);
+
+ /* Release the reference to the new page. */
+ releasePage(pNew);
+ }
- /* Create a divider cell to insert into pParent. The divider cell
- ** consists of a 4-byte page number (the page number of pPage) and
- ** a variable length key value (which must be the same value as the
- ** largest key on pPage).
- **
- ** To find the largest key value on pPage, first find the right-most
- ** cell on pPage. The first two fields of this cell are the
- ** record-length (a variable length integer at most 32-bits in size)
- ** and the key value (a variable length integer, may have any value).
- ** The first of the while(...) loops below skips over the record-length
- ** field. The second while(...) loop copies the key value from the
- ** cell on pPage into the pSpace buffer.
- */
- int iCell = findCell( pPage, pPage.nCell - 1 ); //pCell = findCell( pPage, pPage.nCell - 1 );
- pCell = pPage.aData;
- int _pCell = iCell;
- pStop = _pCell + 9; //pStop = &pCell[9];
- while ( ( ( pCell[_pCell++] ) & 0x80 ) != 0 && _pCell < pStop )
- ; //while ( ( *( pCell++ ) & 0x80 ) && pCell < pStop ) ;
- pStop = _pCell + 9;//pStop = &pCell[9];
- while ( ( ( pSpace[pOut++] = pCell[_pCell++] ) & 0x80 ) != 0 && _pCell < pStop )
- ; //while ( ( ( *( pOut++ ) = *( pCell++ ) ) & 0x80 ) && pCell < pStop ) ;
-
- /* Insert the new divider cell into pParent. */
- insertCell( pParent, pParent.nCell, pSpace, pOut, //(int)(pOut-pSpace),
- null, pPage.pgno, ref rc );
-
- /* Set the right-child pointer of pParent to point to the new page. */
- sqlite3Put4byte( pParent.aData, pParent.hdrOffset + 8, pgnoNew );
-
- /* Release the reference to the new page. */
- releasePage( pNew );
- }
-
- return rc;
-}
+ return rc;
+ }
#endif //* SQLITE_OMIT_QUICKBALANCE */
#if FALSE
@@ -6731,815 +6111,746 @@ static int ptrmapCheckPages(MemPage **apPage, int nPage){
}
#endif
-/*
-** This function is used to copy the contents of the b-tree node stored
-** on page pFrom to page pTo. If page pFrom was not a leaf page, then
-** the pointer-map entries for each child page are updated so that the
-** parent page stored in the pointer map is page pTo. If pFrom contained
-** any cells with overflow page pointers, then the corresponding pointer
-** map entries are also updated so that the parent page is page pTo.
-**
-** If pFrom is currently carrying any overflow cells (entries in the
-** MemPage.aOvfl[] array), they are not copied to pTo.
-**
-** Before returning, page pTo is reinitialized using btreeInitPage().
-**
-** The performance of this function is not critical. It is only used by
-** the balance_shallower() and balance_deeper() procedures, neither of
-** which are called often under normal circumstances.
-*/
-static void copyNodeContent( MemPage pFrom, MemPage pTo, ref int pRC )
-{
- if ( ( pRC ) == SQLITE_OK )
- {
- BtShared pBt = pFrom.pBt;
- u8[] aFrom = pFrom.aData;
- u8[] aTo = pTo.aData;
- int iFromHdr = pFrom.hdrOffset;
- int iToHdr = ( ( pTo.pgno == 1 ) ? 100 : 0 );
- int rc;
- int iData;
-
-
- Debug.Assert( pFrom.isInit != 0 );
- Debug.Assert( pFrom.nFree >= iToHdr );
- Debug.Assert( get2byte( aFrom, iFromHdr + 5 ) <= (int)pBt.usableSize );
-
- /* Copy the b-tree node content from page pFrom to page pTo. */
- iData = get2byte( aFrom, iFromHdr + 5 );
- Buffer.BlockCopy( aFrom, iData, aTo, iData, (int)pBt.usableSize - iData );//memcpy(aTo[iData], ref aFrom[iData], pBt.usableSize-iData);
- Buffer.BlockCopy( aFrom, iFromHdr, aTo, iToHdr, pFrom.cellOffset + 2 * pFrom.nCell );//memcpy(aTo[iToHdr], ref aFrom[iFromHdr], pFrom.cellOffset + 2*pFrom.nCell);
-
- /* Reinitialize page pTo so that the contents of the MemPage structure
- ** match the new data. The initialization of pTo can actually fail under
- ** fairly obscure circumstances, even though it is a copy of initialized
- ** page pFrom.
- */
- pTo.isInit = 0;
- rc = btreeInitPage( pTo );
- if ( rc != SQLITE_OK )
- {
- pRC = rc;
- return;
- }
-
- /* If this is an auto-vacuum database, update the pointer-map entries
- ** for any b-tree or overflow pages that pTo now contains the pointers to.
- */
+ /*
+ ** This function is used to copy the contents of the b-tree node stored
+ ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
+ ** the pointer-map entries for each child page are updated so that the
+ ** parent page stored in the pointer map is page pTo. If pFrom contained
+ ** any cells with overflow page pointers, then the corresponding pointer
+ ** map entries are also updated so that the parent page is page pTo.
+ **
+ ** If pFrom is currently carrying any overflow cells (entries in the
+ ** MemPage.aOvfl[] array), they are not copied to pTo.
+ **
+ ** Before returning, page pTo is reinitialized using btreeInitPage().
+ **
+ ** The performance of this function is not critical. It is only used by
+ ** the balance_shallower() and balance_deeper() procedures, neither of
+ ** which are called often under normal circumstances.
+ */
+ static void copyNodeContent(MemPage pFrom, MemPage pTo, ref int pRC) {
+ if ((pRC) == SQLITE_OK) {
+ BtShared pBt = pFrom.pBt;
+ u8[] aFrom = pFrom.aData;
+ u8[] aTo = pTo.aData;
+ int iFromHdr = pFrom.hdrOffset;
+ int iToHdr = ((pTo.pgno == 1) ? 100 : 0);
+ int rc;
+ int iData;
+
+
+ Debug.Assert(pFrom.isInit != 0);
+ Debug.Assert(pFrom.nFree >= iToHdr);
+ Debug.Assert(get2byte(aFrom, iFromHdr + 5) <= (int)pBt.usableSize);
+
+ /* Copy the b-tree node content from page pFrom to page pTo. */
+ iData = get2byte(aFrom, iFromHdr + 5);
+ Buffer.BlockCopy(aFrom, iData, aTo, iData, (int)pBt.usableSize - iData);//memcpy(aTo[iData], ref aFrom[iData], pBt.usableSize-iData);
+ Buffer.BlockCopy(aFrom, iFromHdr, aTo, iToHdr, pFrom.cellOffset + 2 * pFrom.nCell);//memcpy(aTo[iToHdr], ref aFrom[iFromHdr], pFrom.cellOffset + 2*pFrom.nCell);
+
+ /* Reinitialize page pTo so that the contents of the MemPage structure
+ ** match the new data. The initialization of pTo can actually fail under
+ ** fairly obscure circumstances, even though it is a copy of initialized
+ ** page pFrom.
+ */
+ pTo.isInit = 0;
+ rc = btreeInitPage(pTo);
+ if (rc != SQLITE_OK) {
+ pRC = rc;
+ return;
+ }
+
+ /* If this is an auto-vacuum database, update the pointer-map entries
+ ** for any b-tree or overflow pages that pTo now contains the pointers to.
+ */
#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM )
- if ( pBt.autoVacuum )
+ if (pBt.autoVacuum)
#else
if (false)
#endif
- {
- pRC = setChildPtrmaps( pTo );
- }
- }
-}
-
-/*
-** This routine redistributes cells on the iParentIdx'th child of pParent
-** (hereafter "the page") and up to 2 siblings so that all pages have about the
-** same amount of free space. Usually a single sibling on either side of the
-** page are used in the balancing, though both siblings might come from one
-** side if the page is the first or last child of its parent. If the page
-** has fewer than 2 siblings (something which can only happen if the page
-** is a root page or a child of a root page) then all available siblings
-** participate in the balancing.
-**
-** The number of siblings of the page might be increased or decreased by
-** one or two in an effort to keep pages nearly full but not over full.
-**
-** Note that when this routine is called, some of the cells on the page
-** might not actually be stored in MemPage.aData[]. This can happen
-** if the page is overfull. This routine ensures that all cells allocated
-** to the page and its siblings fit into MemPage.aData[] before returning.
-**
-** In the course of balancing the page and its siblings, cells may be
-** inserted into or removed from the parent page (pParent). Doing so
-** may cause the parent page to become overfull or underfull. If this
-** happens, it is the responsibility of the caller to invoke the correct
-** balancing routine to fix this problem (see the balance() routine).
-**
-** If this routine fails for any reason, it might leave the database
-** in a corrupted state. So if this routine fails, the database should
-** be rolled back.
-**
-** The third argument to this function, aOvflSpace, is a pointer to a
-** buffer big enough to hold one page. If while inserting cells into the parent
-** page (pParent) the parent page becomes overfull, this buffer is
-** used to store the parent's overflow cells. Because this function inserts
-** a maximum of four divider cells into the parent page, and the maximum
-** size of a cell stored within an internal node is always less than 1/4
-** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
-** enough for all overflow cells.
-**
-** If aOvflSpace is set to a null pointer, this function returns
-** SQLITE_NOMEM.
-*/
+ {
+ pRC = setChildPtrmaps(pTo);
+ }
+ }
+ }
-// under C#; Try to reuse Memory
+ /*
+ ** This routine redistributes cells on the iParentIdx'th child of pParent
+ ** (hereafter "the page") and up to 2 siblings so that all pages have about the
+ ** same amount of free space. Usually a single sibling on either side of the
+ ** page are used in the balancing, though both siblings might come from one
+ ** side if the page is the first or last child of its parent. If the page
+ ** has fewer than 2 siblings (something which can only happen if the page
+ ** is a root page or a child of a root page) then all available siblings
+ ** participate in the balancing.
+ **
+ ** The number of siblings of the page might be increased or decreased by
+ ** one or two in an effort to keep pages nearly full but not over full.
+ **
+ ** Note that when this routine is called, some of the cells on the page
+ ** might not actually be stored in MemPage.aData[]. This can happen
+ ** if the page is overfull. This routine ensures that all cells allocated
+ ** to the page and its siblings fit into MemPage.aData[] before returning.
+ **
+ ** In the course of balancing the page and its siblings, cells may be
+ ** inserted into or removed from the parent page (pParent). Doing so
+ ** may cause the parent page to become overfull or underfull. If this
+ ** happens, it is the responsibility of the caller to invoke the correct
+ ** balancing routine to fix this problem (see the balance() routine).
+ **
+ ** If this routine fails for any reason, it might leave the database
+ ** in a corrupted state. So if this routine fails, the database should
+ ** be rolled back.
+ **
+ ** The third argument to this function, aOvflSpace, is a pointer to a
+ ** buffer big enough to hold one page. If while inserting cells into the parent
+ ** page (pParent) the parent page becomes overfull, this buffer is
+ ** used to store the parent's overflow cells. Because this function inserts
+ ** a maximum of four divider cells into the parent page, and the maximum
+ ** size of a cell stored within an internal node is always less than 1/4
+ ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
+ ** enough for all overflow cells.
+ **
+ ** If aOvflSpace is set to a null pointer, this function returns
+ ** SQLITE_NOMEM.
+ */
-static int balance_nonroot(
-MemPage pParent, /* Parent page of siblings being balanced */
-int iParentIdx, /* Index of "the page" in pParent */
-u8[] aOvflSpace, /* page-size bytes of space for parent ovfl */
-int isRoot /* True if pParent is a root-page */
-)
-{
- MemPage[] apOld = new MemPage[NB]; /* pPage and up to two siblings */
- MemPage[] apCopy = new MemPage[NB]; /* Private copies of apOld[] pages */
- MemPage[] apNew = new MemPage[NB + 2];/* pPage and up to NB siblings after balancing */
- int[] apDiv = new int[NB - 1]; /* Divider cells in pParent */
- int[] cntNew = new int[NB + 2]; /* Index in aCell[] of cell after i-th page */
- int[] szNew = new int[NB + 2]; /* Combined size of cells place on i-th page */
- u16[] szCell = new u16[1]; /* Local size of all cells in apCell[] */
- BtShared pBt; /* The whole database */
- int nCell = 0; /* Number of cells in apCell[] */
- int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
- int nNew = 0; /* Number of pages in apNew[] */
- int nOld; /* Number of pages in apOld[] */
- int i, j, k; /* Loop counters */
- int nxDiv; /* Next divider slot in pParent.aCell[] */
- int rc = SQLITE_OK; /* The return code */
- u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
- int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
- int usableSpace; /* Bytes in pPage beyond the header */
- int pageFlags; /* Value of pPage.aData[0] */
- int subtotal; /* Subtotal of bytes in cells on one page */
- //int iSpace1 = 0; /* First unused byte of aSpace1[] */
- int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
- int szScratch; /* Size of scratch memory requested */
- int pRight; /* Location in parent of right-sibling pointer */
- u8[][] apCell = null; /* All cells begin balanced */
- //u16[] szCell; /* Local size of all cells in apCell[] */
- //u8[] aSpace1; /* Space for copies of dividers cells */
- Pgno pgno; /* Temp var to store a page number in */
-
- pBt = pParent.pBt;
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- Debug.Assert( sqlite3PagerIswriteable( pParent.pDbPage ) );
+ // under C#; Try to reuse Memory
+
+ static int balance_nonroot(
+ MemPage pParent, /* Parent page of siblings being balanced */
+ int iParentIdx, /* Index of "the page" in pParent */
+ u8[] aOvflSpace, /* page-size bytes of space for parent ovfl */
+ int isRoot /* True if pParent is a root-page */
+ ) {
+ MemPage[] apOld = new MemPage[NB]; /* pPage and up to two siblings */
+ MemPage[] apCopy = new MemPage[NB]; /* Private copies of apOld[] pages */
+ MemPage[] apNew = new MemPage[NB + 2];/* pPage and up to NB siblings after balancing */
+ int[] apDiv = new int[NB - 1]; /* Divider cells in pParent */
+ int[] cntNew = new int[NB + 2]; /* Index in aCell[] of cell after i-th page */
+ int[] szNew = new int[NB + 2]; /* Combined size of cells place on i-th page */
+ u16[] szCell = new u16[1]; /* Local size of all cells in apCell[] */
+ BtShared pBt; /* The whole database */
+ int nCell = 0; /* Number of cells in apCell[] */
+ int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
+ int nNew = 0; /* Number of pages in apNew[] */
+ int nOld; /* Number of pages in apOld[] */
+ int i, j, k; /* Loop counters */
+ int nxDiv; /* Next divider slot in pParent.aCell[] */
+ int rc = SQLITE_OK; /* The return code */
+ u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
+ int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
+ int usableSpace; /* Bytes in pPage beyond the header */
+ int pageFlags; /* Value of pPage.aData[0] */
+ int subtotal; /* Subtotal of bytes in cells on one page */
+ //int iSpace1 = 0; /* First unused byte of aSpace1[] */
+ int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
+ int szScratch; /* Size of scratch memory requested */
+ int pRight; /* Location in parent of right-sibling pointer */
+ u8[][] apCell = null; /* All cells begin balanced */
+ //u16[] szCell; /* Local size of all cells in apCell[] */
+ //u8[] aSpace1; /* Space for copies of dividers cells */
+ Pgno pgno; /* Temp var to store a page number in */
+
+ pBt = pParent.pBt;
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage));
#if FALSE
TRACE("BALANCE: begin page %d child of %d\n", pPage.pgno, pParent.pgno);
#endif
- /* At this point pParent may have at most one overflow cell. And if
-** this overflow cell is present, it must be the cell with
-** index iParentIdx. This scenario comes about when this function
-** is called (indirectly) from sqlite3BtreeDelete().
-*/
- Debug.Assert( pParent.nOverflow == 0 || pParent.nOverflow == 1 );
- Debug.Assert( pParent.nOverflow == 0 || pParent.aOvfl[0].idx == iParentIdx );
-
- //if( !aOvflSpace ){
- // return SQLITE_NOMEM;
- //}
-
- /* Find the sibling pages to balance. Also locate the cells in pParent
- ** that divide the siblings. An attempt is made to find NN siblings on
- ** either side of pPage. More siblings are taken from one side, however,
- ** if there are fewer than NN siblings on the other side. If pParent
- ** has NB or fewer children then all children of pParent are taken.
- **
- ** This loop also drops the divider cells from the parent page. This
- ** way, the remainder of the function does not have to deal with any
- ** overflow cells in the parent page, since if any existed they will
- ** have already been removed.
- */
- i = pParent.nOverflow + pParent.nCell;
- if ( i < 2 )
- {
- nxDiv = 0;
- nOld = i + 1;
- }
- else
- {
- nOld = 3;
- if ( iParentIdx == 0 )
- {
- nxDiv = 0;
- }
- else if ( iParentIdx == i )
- {
- nxDiv = i - 2;
- }
- else
- {
- nxDiv = iParentIdx - 1;
- }
- i = 2;
- }
- if ( ( i + nxDiv - pParent.nOverflow ) == pParent.nCell )
- {
- pRight = pParent.hdrOffset + 8; //&pParent.aData[pParent.hdrOffset + 8];
- }
- else
- {
- pRight = findCell( pParent, i + nxDiv - pParent.nOverflow );
- }
- pgno = sqlite3Get4byte( pParent.aData, pRight );
- while ( true )
- {
- rc = getAndInitPage( pBt, pgno, ref apOld[i] );
- if ( rc != 0 )
- {
- //memset(apOld, 0, (i+1)*sizeof(MemPage*));
- goto balance_cleanup;
- }
- nMaxCells += 1 + apOld[i].nCell + apOld[i].nOverflow;
- if ( ( i-- ) == 0 )
- break;
+ /* At this point pParent may have at most one overflow cell. And if
+ ** this overflow cell is present, it must be the cell with
+ ** index iParentIdx. This scenario comes about when this function
+ ** is called (indirectly) from sqlite3BtreeDelete().
+ */
+ Debug.Assert(pParent.nOverflow == 0 || pParent.nOverflow == 1);
+ Debug.Assert(pParent.nOverflow == 0 || pParent.aOvfl[0].idx == iParentIdx);
+
+ //if( !aOvflSpace ){
+ // return SQLITE_NOMEM;
+ //}
+
+ /* Find the sibling pages to balance. Also locate the cells in pParent
+ ** that divide the siblings. An attempt is made to find NN siblings on
+ ** either side of pPage. More siblings are taken from one side, however,
+ ** if there are fewer than NN siblings on the other side. If pParent
+ ** has NB or fewer children then all children of pParent are taken.
+ **
+ ** This loop also drops the divider cells from the parent page. This
+ ** way, the remainder of the function does not have to deal with any
+ ** overflow cells in the parent page, since if any existed they will
+ ** have already been removed.
+ */
+ i = pParent.nOverflow + pParent.nCell;
+ if (i < 2) {
+ nxDiv = 0;
+ nOld = i + 1;
+ } else {
+ nOld = 3;
+ if (iParentIdx == 0) {
+ nxDiv = 0;
+ } else if (iParentIdx == i) {
+ nxDiv = i - 2;
+ } else {
+ nxDiv = iParentIdx - 1;
+ }
+ i = 2;
+ }
+ if ((i + nxDiv - pParent.nOverflow) == pParent.nCell) {
+ pRight = pParent.hdrOffset + 8; //&pParent.aData[pParent.hdrOffset + 8];
+ } else {
+ pRight = findCell(pParent, i + nxDiv - pParent.nOverflow);
+ }
+ pgno = sqlite3Get4byte(pParent.aData, pRight);
+ while (true) {
+ rc = getAndInitPage(pBt, pgno, ref apOld[i]);
+ if (rc != 0) {
+ //memset(apOld, 0, (i+1)*sizeof(MemPage*));
+ goto balance_cleanup;
+ }
+ nMaxCells += 1 + apOld[i].nCell + apOld[i].nOverflow;
+ if ((i--) == 0)
+ break;
+
+ if (i + nxDiv == pParent.aOvfl[0].idx && pParent.nOverflow != 0) {
+ apDiv[i] = 0;// = pParent.aOvfl[0].pCell;
+ pgno = sqlite3Get4byte(pParent.aOvfl[0].pCell, apDiv[i]);
+ szNew[i] = cellSizePtr(pParent, apDiv[i]);
+ pParent.nOverflow = 0;
+ } else {
+ apDiv[i] = findCell(pParent, i + nxDiv - pParent.nOverflow);
+ pgno = sqlite3Get4byte(pParent.aData, apDiv[i]);
+ szNew[i] = cellSizePtr(pParent, apDiv[i]);
+
+ /* Drop the cell from the parent page. apDiv[i] still points to
+ ** the cell within the parent, even though it has been dropped.
+ ** This is safe because dropping a cell only overwrites the first
+ ** four bytes of it, and this function does not need the first
+ ** four bytes of the divider cell. So the pointer is safe to use
+ ** later on.
+ **
+ ** Unless SQLite is compiled in secure-delete mode. In this case,
+ ** the dropCell() routine will overwrite the entire cell with zeroes.
+ ** In this case, temporarily copy the cell into the aOvflSpace[]
+ ** buffer. It will be copied out again as soon as the aSpace[] buffer
+ ** is allocated. */
+ //if (pBt.secureDelete)
+ //{
+ // int iOff = (int)(apDiv[i]) - (int)(pParent.aData); //SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent.aData);
+ // if( (iOff+szNew[i])>(int)pBt->usableSize )
+ // {
+ // rc = SQLITE_CORRUPT_BKPT();
+ // Array.Clear(apOld[0].aData,0,apOld[0].aData.Length); //memset(apOld, 0, (i + 1) * sizeof(MemPage*));
+ // goto balance_cleanup;
+ // }
+ // else
+ // {
+ // memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
+ // apDiv[i] = &aOvflSpace[apDiv[i] - pParent.aData];
+ // }
+ //}
+ dropCell(pParent, i + nxDiv - pParent.nOverflow, szNew[i], ref rc);
+ }
+ }
- if ( i + nxDiv == pParent.aOvfl[0].idx && pParent.nOverflow != 0 )
- {
- apDiv[i] = 0;// = pParent.aOvfl[0].pCell;
- pgno = sqlite3Get4byte( pParent.aOvfl[0].pCell, apDiv[i] );
- szNew[i] = cellSizePtr( pParent, apDiv[i] );
- pParent.nOverflow = 0;
- }
- else
- {
- apDiv[i] = findCell( pParent, i + nxDiv - pParent.nOverflow );
- pgno = sqlite3Get4byte( pParent.aData, apDiv[i] );
- szNew[i] = cellSizePtr( pParent, apDiv[i] );
-
- /* Drop the cell from the parent page. apDiv[i] still points to
- ** the cell within the parent, even though it has been dropped.
- ** This is safe because dropping a cell only overwrites the first
- ** four bytes of it, and this function does not need the first
- ** four bytes of the divider cell. So the pointer is safe to use
- ** later on.
- **
- ** Unless SQLite is compiled in secure-delete mode. In this case,
- ** the dropCell() routine will overwrite the entire cell with zeroes.
- ** In this case, temporarily copy the cell into the aOvflSpace[]
- ** buffer. It will be copied out again as soon as the aSpace[] buffer
- ** is allocated. */
- //if (pBt.secureDelete)
- //{
- // int iOff = (int)(apDiv[i]) - (int)(pParent.aData); //SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent.aData);
- // if( (iOff+szNew[i])>(int)pBt->usableSize )
- // {
- // rc = SQLITE_CORRUPT_BKPT();
- // Array.Clear(apOld[0].aData,0,apOld[0].aData.Length); //memset(apOld, 0, (i + 1) * sizeof(MemPage*));
- // goto balance_cleanup;
- // }
- // else
- // {
- // memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
- // apDiv[i] = &aOvflSpace[apDiv[i] - pParent.aData];
- // }
- //}
- dropCell( pParent, i + nxDiv - pParent.nOverflow, szNew[i], ref rc );
- }
- }
-
- /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
- ** alignment */
- nMaxCells = ( nMaxCells + 3 ) & ~3;
-
- /*
- ** Allocate space for memory structures
- */
- //k = pBt.pageSize + ROUND8(sizeof(MemPage));
- //szScratch =
- // nMaxCells*sizeof(u8*) /* apCell */
- // + nMaxCells*sizeof(u16) /* szCell */
- // + pBt.pageSize /* aSpace1 */
- // + k*nOld; /* Page copies (apCopy) */
- apCell = sqlite3ScratchMalloc( apCell, nMaxCells );
- //if( apCell==null ){
- // rc = SQLITE_NOMEM;
- // goto balance_cleanup;
- //}
- if ( szCell.Length < nMaxCells )
- Array.Resize( ref szCell, nMaxCells ); //(u16*)&apCell[nMaxCells];
- //aSpace1 = new byte[pBt.pageSize * (nMaxCells)];// aSpace1 = (u8*)&szCell[nMaxCells];
- //Debug.Assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
-
- /*
- ** Load pointers to all cells on sibling pages and the divider cells
- ** into the local apCell[] array. Make copies of the divider cells
- ** into space obtained from aSpace1[] and remove the the divider Cells
- ** from pParent.
- **
- ** If the siblings are on leaf pages, then the child pointers of the
- ** divider cells are stripped from the cells before they are copied
- ** into aSpace1[]. In this way, all cells in apCell[] are without
- ** child pointers. If siblings are not leaves, then all cell in
- ** apCell[] include child pointers. Either way, all cells in apCell[]
- ** are alike.
- **
- ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
- ** leafData: 1 if pPage holds key+data and pParent holds only keys.
- */
- leafCorrection = (u16)( apOld[0].leaf * 4 );
- leafData = apOld[0].hasData;
- for ( i = 0; i < nOld; i++ )
- {
- int limit;
-
- /* Before doing anything else, take a copy of the i'th original sibling
- ** The rest of this function will use data from the copies rather
- ** that the original pages since the original pages will be in the
- ** process of being overwritten. */
- //MemPage pOld = apCopy[i] = (MemPage*)&aSpace1[pBt.pageSize + k*i];
- //memcpy(pOld, apOld[i], sizeof(MemPage));
- //pOld.aData = (void*)&pOld[1];
- //memcpy(pOld.aData, apOld[i].aData, pBt.pageSize);
- MemPage pOld = apCopy[i] = apOld[i].Copy();
-
- limit = pOld.nCell + pOld.nOverflow;
- if( pOld.nOverflow>0 || true){
- for ( j = 0; j < limit; j++ )
- {
- Debug.Assert( nCell < nMaxCells );
- //apCell[nCell] = findOverflowCell( pOld, j );
- //szCell[nCell] = cellSizePtr( pOld, apCell, nCell );
- int iFOFC = findOverflowCell( pOld, j );
- szCell[nCell] = cellSizePtr( pOld, iFOFC );
- // Copy the Data Locally
- if ( apCell[nCell] == null )
- apCell[nCell] = new u8[szCell[nCell]];
- else if ( apCell[nCell].Length < szCell[nCell] )
- Array.Resize( ref apCell[nCell], szCell[nCell] );
- if ( iFOFC < 0 ) // Overflow Cell
- Buffer.BlockCopy( pOld.aOvfl[-( iFOFC + 1 )].pCell, 0, apCell[nCell], 0, szCell[nCell] );
- else
- Buffer.BlockCopy( pOld.aData, iFOFC, apCell[nCell], 0, szCell[nCell] );
- nCell++;
- }
- }
- else
- {
- u8[] aData = pOld.aData;
- u16 maskPage = pOld.maskPage;
- u16 cellOffset = pOld.cellOffset;
- for ( j = 0; j < limit; j++ )
- {
- Debugger.Break();
- Debug.Assert( nCell < nMaxCells );
- apCell[nCell] = findCellv2( aData, maskPage, cellOffset, j );
- szCell[nCell] = cellSizePtr( pOld, apCell[nCell] );
- nCell++;
- }
- }
- if ( i < nOld - 1 && 0 == leafData )
- {
- u16 sz = (u16)szNew[i];
- byte[] pTemp = sqlite3Malloc( sz + leafCorrection );
- Debug.Assert( nCell < nMaxCells );
- szCell[nCell] = sz;
- //pTemp = &aSpace1[iSpace1];
- //iSpace1 += sz;
- Debug.Assert( sz <= pBt.maxLocal + 23 );
- //Debug.Assert(iSpace1 <= (int)pBt.pageSize);
- Buffer.BlockCopy( pParent.aData, apDiv[i], pTemp, 0, sz );//memcpy( pTemp, apDiv[i], sz );
- if ( apCell[nCell] == null || apCell[nCell].Length < sz )
- Array.Resize( ref apCell[nCell], sz );
- Buffer.BlockCopy( pTemp, leafCorrection, apCell[nCell], 0, sz );//apCell[nCell] = pTemp + leafCorrection;
- Debug.Assert( leafCorrection == 0 || leafCorrection == 4 );
- szCell[nCell] = (u16)( szCell[nCell] - leafCorrection );
- if ( 0 == pOld.leaf )
- {
- Debug.Assert( leafCorrection == 0 );
- Debug.Assert( pOld.hdrOffset == 0 );
- /* The right pointer of the child page pOld becomes the left
- ** pointer of the divider cell */
- Buffer.BlockCopy( pOld.aData, 8, apCell[nCell], 0, 4 );//memcpy( apCell[nCell], ref pOld.aData[8], 4 );
- }
- else
- {
- Debug.Assert( leafCorrection == 4 );
- if ( szCell[nCell] < 4 )
- {
- /* Do not allow any cells smaller than 4 bytes. */
- szCell[nCell] = 4;
- }
- }
- nCell++;
- }
- }
-
- /*
- ** Figure out the number of pages needed to hold all nCell cells.
- ** Store this number in "k". Also compute szNew[] which is the total
- ** size of all cells on the i-th page and cntNew[] which is the index
- ** in apCell[] of the cell that divides page i from page i+1.
- ** cntNew[k] should equal nCell.
- **
- ** Values computed by this block:
- **
- ** k: The total number of sibling pages
- ** szNew[i]: Spaced used on the i-th sibling page.
- ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
- ** the right of the i-th sibling page.
- ** usableSpace: Number of bytes of space available on each sibling.
- **
- */
- usableSpace = (int)pBt.usableSize - 12 + leafCorrection;
- for ( subtotal = k = i = 0; i < nCell; i++ )
- {
- Debug.Assert( i < nMaxCells );
- subtotal += szCell[i] + 2;
- if ( subtotal > usableSpace )
- {
- szNew[k] = subtotal - szCell[i];
- cntNew[k] = i;
- if ( leafData != 0 )
- {
- i--;
- }
- subtotal = 0;
- k++;
- if ( k > NB + 1 )
- {
- rc = SQLITE_CORRUPT_BKPT();
- goto balance_cleanup;
- }
- }
- }
- szNew[k] = subtotal;
- cntNew[k] = nCell;
- k++;
-
- /*
- ** The packing computed by the previous block is biased toward the siblings
- ** on the left side. The left siblings are always nearly full, while the
- ** right-most sibling might be nearly empty. This block of code attempts
- ** to adjust the packing of siblings to get a better balance.
- **
- ** This adjustment is more than an optimization. The packing above might
- ** be so out of balance as to be illegal. For example, the right-most
- ** sibling might be completely empty. This adjustment is not optional.
- */
- for ( i = k - 1; i > 0; i-- )
- {
- int szRight = szNew[i]; /* Size of sibling on the right */
- int szLeft = szNew[i - 1]; /* Size of sibling on the left */
- int r; /* Index of right-most cell in left sibling */
- int d; /* Index of first cell to the left of right sibling */
-
- r = cntNew[i - 1] - 1;
- d = r + 1 - leafData;
- Debug.Assert( d < nMaxCells );
- Debug.Assert( r < nMaxCells );
- while ( szRight == 0 || szRight + szCell[d] + 2 <= szLeft - ( szCell[r] + 2 ) )
- {
- szRight += szCell[d] + 2;
- szLeft -= szCell[r] + 2;
- cntNew[i - 1]--;
- r = cntNew[i - 1] - 1;
- d = r + 1 - leafData;
- }
- szNew[i] = szRight;
- szNew[i - 1] = szLeft;
- }
-
- /* Either we found one or more cells (cntnew[0])>0) or pPage is
- ** a virtual root page. A virtual root page is when the real root
- ** page is page 1 and we are the only child of that page.
- */
- Debug.Assert( cntNew[0] > 0 || ( pParent.pgno == 1 && pParent.nCell == 0 ) );
-
- TRACE( "BALANCE: old: %d %d %d ",
- apOld[0].pgno,
- nOld >= 2 ? apOld[1].pgno : 0,
- nOld >= 3 ? apOld[2].pgno : 0
- );
-
- /*
- ** Allocate k new pages. Reuse old pages where possible.
- */
- if ( apOld[0].pgno <= 1 )
- {
- rc = SQLITE_CORRUPT_BKPT();
- goto balance_cleanup;
- }
- pageFlags = apOld[0].aData[0];
- for ( i = 0; i < k; i++ )
- {
- MemPage pNew = new MemPage();
- if ( i < nOld )
- {
- pNew = apNew[i] = apOld[i];
- apOld[i] = null;
- rc = sqlite3PagerWrite( pNew.pDbPage );
- nNew++;
- if ( rc != 0 )
- goto balance_cleanup;
- }
- else
- {
- Debug.Assert( i > 0 );
- rc = allocateBtreePage( pBt, ref pNew, ref pgno, pgno, 0 );
- if ( rc != 0 )
- goto balance_cleanup;
- apNew[i] = pNew;
- nNew++;
-
- /* Set the pointer-map entry for the new sibling page. */
+ /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
+ ** alignment */
+ nMaxCells = (nMaxCells + 3) & ~3;
+
+ /*
+ ** Allocate space for memory structures
+ */
+ //k = pBt.pageSize + ROUND8(sizeof(MemPage));
+ //szScratch =
+ // nMaxCells*sizeof(u8*) /* apCell */
+ // + nMaxCells*sizeof(u16) /* szCell */
+ // + pBt.pageSize /* aSpace1 */
+ // + k*nOld; /* Page copies (apCopy) */
+ apCell = sqlite3ScratchMalloc(apCell, nMaxCells);
+ //if( apCell==null ){
+ // rc = SQLITE_NOMEM;
+ // goto balance_cleanup;
+ //}
+ if (szCell.Length < nMaxCells)
+ Array.Resize(ref szCell, nMaxCells); //(u16*)&apCell[nMaxCells];
+ //aSpace1 = new byte[pBt.pageSize * (nMaxCells)];// aSpace1 = (u8*)&szCell[nMaxCells];
+ //Debug.Assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
+
+ /*
+ ** Load pointers to all cells on sibling pages and the divider cells
+ ** into the local apCell[] array. Make copies of the divider cells
+ ** into space obtained from aSpace1[] and remove the the divider Cells
+ ** from pParent.
+ **
+ ** If the siblings are on leaf pages, then the child pointers of the
+ ** divider cells are stripped from the cells before they are copied
+ ** into aSpace1[]. In this way, all cells in apCell[] are without
+ ** child pointers. If siblings are not leaves, then all cell in
+ ** apCell[] include child pointers. Either way, all cells in apCell[]
+ ** are alike.
+ **
+ ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
+ ** leafData: 1 if pPage holds key+data and pParent holds only keys.
+ */
+ leafCorrection = (u16)(apOld[0].leaf * 4);
+ leafData = apOld[0].hasData;
+ for (i = 0; i < nOld; i++) {
+ int limit;
+
+ /* Before doing anything else, take a copy of the i'th original sibling
+ ** The rest of this function will use data from the copies rather
+ ** that the original pages since the original pages will be in the
+ ** process of being overwritten. */
+ //MemPage pOld = apCopy[i] = (MemPage*)&aSpace1[pBt.pageSize + k*i];
+ //memcpy(pOld, apOld[i], sizeof(MemPage));
+ //pOld.aData = (void*)&pOld[1];
+ //memcpy(pOld.aData, apOld[i].aData, pBt.pageSize);
+ MemPage pOld = apCopy[i] = apOld[i].Copy();
+
+ limit = pOld.nCell + pOld.nOverflow;
+ if (pOld.nOverflow > 0 || true) {
+ for (j = 0; j < limit; j++) {
+ Debug.Assert(nCell < nMaxCells);
+ //apCell[nCell] = findOverflowCell( pOld, j );
+ //szCell[nCell] = cellSizePtr( pOld, apCell, nCell );
+ int iFOFC = findOverflowCell(pOld, j);
+ szCell[nCell] = cellSizePtr(pOld, iFOFC);
+ // Copy the Data Locally
+ if (apCell[nCell] == null)
+ apCell[nCell] = new u8[szCell[nCell]];
+ else if (apCell[nCell].Length < szCell[nCell])
+ Array.Resize(ref apCell[nCell], szCell[nCell]);
+ if (iFOFC < 0) // Overflow Cell
+ Buffer.BlockCopy(pOld.aOvfl[-(iFOFC + 1)].pCell, 0, apCell[nCell], 0, szCell[nCell]);
+ else
+ Buffer.BlockCopy(pOld.aData, iFOFC, apCell[nCell], 0, szCell[nCell]);
+ nCell++;
+ }
+ } else {
+ u8[] aData = pOld.aData;
+ u16 maskPage = pOld.maskPage;
+ u16 cellOffset = pOld.cellOffset;
+ for (j = 0; j < limit; j++) {
+ Debugger.Break();
+ Debug.Assert(nCell < nMaxCells);
+ apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
+ szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
+ nCell++;
+ }
+ }
+ if (i < nOld - 1 && 0 == leafData) {
+ u16 sz = (u16)szNew[i];
+ byte[] pTemp = sqlite3Malloc(sz + leafCorrection);
+ Debug.Assert(nCell < nMaxCells);
+ szCell[nCell] = sz;
+ //pTemp = &aSpace1[iSpace1];
+ //iSpace1 += sz;
+ Debug.Assert(sz <= pBt.maxLocal + 23);
+ //Debug.Assert(iSpace1 <= (int)pBt.pageSize);
+ Buffer.BlockCopy(pParent.aData, apDiv[i], pTemp, 0, sz);//memcpy( pTemp, apDiv[i], sz );
+ if (apCell[nCell] == null || apCell[nCell].Length < sz)
+ Array.Resize(ref apCell[nCell], sz);
+ Buffer.BlockCopy(pTemp, leafCorrection, apCell[nCell], 0, sz);//apCell[nCell] = pTemp + leafCorrection;
+ Debug.Assert(leafCorrection == 0 || leafCorrection == 4);
+ szCell[nCell] = (u16)(szCell[nCell] - leafCorrection);
+ if (0 == pOld.leaf) {
+ Debug.Assert(leafCorrection == 0);
+ Debug.Assert(pOld.hdrOffset == 0);
+ /* The right pointer of the child page pOld becomes the left
+ ** pointer of the divider cell */
+ Buffer.BlockCopy(pOld.aData, 8, apCell[nCell], 0, 4);//memcpy( apCell[nCell], ref pOld.aData[8], 4 );
+ } else {
+ Debug.Assert(leafCorrection == 4);
+ if (szCell[nCell] < 4) {
+ /* Do not allow any cells smaller than 4 bytes. */
+ szCell[nCell] = 4;
+ }
+ }
+ nCell++;
+ }
+ }
+
+ /*
+ ** Figure out the number of pages needed to hold all nCell cells.
+ ** Store this number in "k". Also compute szNew[] which is the total
+ ** size of all cells on the i-th page and cntNew[] which is the index
+ ** in apCell[] of the cell that divides page i from page i+1.
+ ** cntNew[k] should equal nCell.
+ **
+ ** Values computed by this block:
+ **
+ ** k: The total number of sibling pages
+ ** szNew[i]: Spaced used on the i-th sibling page.
+ ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
+ ** the right of the i-th sibling page.
+ ** usableSpace: Number of bytes of space available on each sibling.
+ **
+ */
+ usableSpace = (int)pBt.usableSize - 12 + leafCorrection;
+ for (subtotal = k = i = 0; i < nCell; i++) {
+ Debug.Assert(i < nMaxCells);
+ subtotal += szCell[i] + 2;
+ if (subtotal > usableSpace) {
+ szNew[k] = subtotal - szCell[i];
+ cntNew[k] = i;
+ if (leafData != 0) {
+ i--;
+ }
+ subtotal = 0;
+ k++;
+ if (k > NB + 1) {
+ rc = SQLITE_CORRUPT_BKPT();
+ goto balance_cleanup;
+ }
+ }
+ }
+ szNew[k] = subtotal;
+ cntNew[k] = nCell;
+ k++;
+
+ /*
+ ** The packing computed by the previous block is biased toward the siblings
+ ** on the left side. The left siblings are always nearly full, while the
+ ** right-most sibling might be nearly empty. This block of code attempts
+ ** to adjust the packing of siblings to get a better balance.
+ **
+ ** This adjustment is more than an optimization. The packing above might
+ ** be so out of balance as to be illegal. For example, the right-most
+ ** sibling might be completely empty. This adjustment is not optional.
+ */
+ for (i = k - 1; i > 0; i--) {
+ int szRight = szNew[i]; /* Size of sibling on the right */
+ int szLeft = szNew[i - 1]; /* Size of sibling on the left */
+ int r; /* Index of right-most cell in left sibling */
+ int d; /* Index of first cell to the left of right sibling */
+
+ r = cntNew[i - 1] - 1;
+ d = r + 1 - leafData;
+ Debug.Assert(d < nMaxCells);
+ Debug.Assert(r < nMaxCells);
+ while (szRight == 0 || szRight + szCell[d] + 2 <= szLeft - (szCell[r] + 2)) {
+ szRight += szCell[d] + 2;
+ szLeft -= szCell[r] + 2;
+ cntNew[i - 1]--;
+ r = cntNew[i - 1] - 1;
+ d = r + 1 - leafData;
+ }
+ szNew[i] = szRight;
+ szNew[i - 1] = szLeft;
+ }
+
+ /* Either we found one or more cells (cntnew[0])>0) or pPage is
+ ** a virtual root page. A virtual root page is when the real root
+ ** page is page 1 and we are the only child of that page.
+ */
+ Debug.Assert(cntNew[0] > 0 || (pParent.pgno == 1 && pParent.nCell == 0));
+
+ TRACE("BALANCE: old: %d %d %d ",
+ apOld[0].pgno,
+ nOld >= 2 ? apOld[1].pgno : 0,
+ nOld >= 3 ? apOld[2].pgno : 0
+ );
+
+ /*
+ ** Allocate k new pages. Reuse old pages where possible.
+ */
+ if (apOld[0].pgno <= 1) {
+ rc = SQLITE_CORRUPT_BKPT();
+ goto balance_cleanup;
+ }
+ pageFlags = apOld[0].aData[0];
+ for (i = 0; i < k; i++) {
+ MemPage pNew = new MemPage();
+ if (i < nOld) {
+ pNew = apNew[i] = apOld[i];
+ apOld[i] = null;
+ rc = sqlite3PagerWrite(pNew.pDbPage);
+ nNew++;
+ if (rc != 0)
+ goto balance_cleanup;
+ } else {
+ Debug.Assert(i > 0);
+ rc = allocateBtreePage(pBt, ref pNew, ref pgno, pgno, 0);
+ if (rc != 0)
+ goto balance_cleanup;
+ apNew[i] = pNew;
+ nNew++;
+
+ /* Set the pointer-map entry for the new sibling page. */
#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM )
- if ( pBt.autoVacuum )
+ if (pBt.autoVacuum)
#else
if (false)
#endif
- {
- ptrmapPut( pBt, pNew.pgno, PTRMAP_BTREE, pParent.pgno, ref rc );
- if ( rc != SQLITE_OK )
- {
- goto balance_cleanup;
- }
- }
- }
- }
-
- /* Free any old pages that were not reused as new pages.
- */
- while ( i < nOld )
- {
- freePage( apOld[i], ref rc );
- if ( rc != 0 )
- goto balance_cleanup;
- releasePage( apOld[i] );
- apOld[i] = null;
- i++;
- }
-
- /*
- ** Put the new pages in accending order. This helps to
- ** keep entries in the disk file in order so that a scan
- ** of the table is a linear scan through the file. That
- ** in turn helps the operating system to deliver pages
- ** from the disk more rapidly.
- **
- ** An O(n^2) insertion sort algorithm is used, but since
- ** n is never more than NB (a small constant), that should
- ** not be a problem.
- **
- ** When NB==3, this one optimization makes the database
- ** about 25% faster for large insertions and deletions.
- */
- for ( i = 0; i < k - 1; i++ )
- {
- int minV = (int)apNew[i].pgno;
- int minI = i;
- for ( j = i + 1; j < k; j++ )
- {
- if ( apNew[j].pgno < (u32)minV )
- {
- minI = j;
- minV = (int)apNew[j].pgno;
- }
- }
- if ( minI > i )
- {
- MemPage pT;
- pT = apNew[i];
- apNew[i] = apNew[minI];
- apNew[minI] = pT;
- }
- }
- TRACE( "new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
- apNew[0].pgno, szNew[0],
- nNew >= 2 ? apNew[1].pgno : 0, nNew >= 2 ? szNew[1] : 0,
- nNew >= 3 ? apNew[2].pgno : 0, nNew >= 3 ? szNew[2] : 0,
- nNew >= 4 ? apNew[3].pgno : 0, nNew >= 4 ? szNew[3] : 0,
- nNew >= 5 ? apNew[4].pgno : 0, nNew >= 5 ? szNew[4] : 0 );
-
- Debug.Assert( sqlite3PagerIswriteable( pParent.pDbPage ) );
- sqlite3Put4byte( pParent.aData, pRight, apNew[nNew - 1].pgno );
-
- /*
- ** Evenly distribute the data in apCell[] across the new pages.
- ** Insert divider cells into pParent as necessary.
- */
- j = 0;
- for ( i = 0; i < nNew; i++ )
- {
- /* Assemble the new sibling page. */
- MemPage pNew = apNew[i];
- Debug.Assert( j < nMaxCells );
- zeroPage( pNew, pageFlags );
- assemblePage( pNew, cntNew[i] - j, apCell, szCell, j );
- Debug.Assert( pNew.nCell > 0 || ( nNew == 1 && cntNew[0] == 0 ) );
- Debug.Assert( pNew.nOverflow == 0 );
-
- j = cntNew[i];
-
- /* If the sibling page assembled above was not the right-most sibling,
- ** insert a divider cell into the parent page.
- */
- Debug.Assert( i < nNew - 1 || j == nCell );
- if ( j < nCell )
- {
- u8[] pCell;
- u8[] pTemp;
- int sz;
-
- Debug.Assert( j < nMaxCells );
- pCell = apCell[j];
- sz = szCell[j] + leafCorrection;
- pTemp = sqlite3Malloc( sz );//&aOvflSpace[iOvflSpace];
- if ( 0 == pNew.leaf )
- {
- Buffer.BlockCopy( pCell, 0, pNew.aData, 8, 4 );//memcpy( pNew.aData[8], pCell, 4 );
- }
- else if ( leafData != 0 )
- {
- /* If the tree is a leaf-data tree, and the siblings are leaves,
- ** then there is no divider cell in apCell[]. Instead, the divider
- ** cell consists of the integer key for the right-most cell of
- ** the sibling-page assembled above only.
- */
- CellInfo info = new CellInfo();
- j--;
- btreeParseCellPtr( pNew, apCell[j], ref info );
- pCell = pTemp;
- sz = 4 + putVarint( pCell, 4, (u64)info.nKey );
- pTemp = null;
- }
- else
- {
- //------------ pCell -= 4;
- byte[] _pCell_4 = sqlite3Malloc( pCell.Length + 4 );
- Buffer.BlockCopy( pCell, 0, _pCell_4, 4, pCell.Length );
- pCell = _pCell_4;
- //
- /* Obscure case for non-leaf-data trees: If the cell at pCell was
- ** previously stored on a leaf node, and its reported size was 4
- ** bytes, then it may actually be smaller than this
- ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
- ** any cell). But it is important to pass the correct size to
- ** insertCell(), so reparse the cell now.
- **
- ** Note that this can never happen in an SQLite data file, as all
- ** cells are at least 4 bytes. It only happens in b-trees used
- ** to evaluate "IN (SELECT ...)" and similar clauses.
- */
- if ( szCell[j] == 4 )
- {
- Debug.Assert( leafCorrection == 4 );
- sz = cellSizePtr( pParent, pCell );
- }
- }
- iOvflSpace += sz;
- Debug.Assert( sz <= pBt.maxLocal + 23 );
- Debug.Assert( iOvflSpace <= (int)pBt.pageSize );
- insertCell( pParent, nxDiv, pCell, sz, pTemp, pNew.pgno, ref rc );
- if ( rc != SQLITE_OK )
- goto balance_cleanup;
- Debug.Assert( sqlite3PagerIswriteable( pParent.pDbPage ) );
-
- j++;
- nxDiv++;
- }
- }
- Debug.Assert( j == nCell );
- Debug.Assert( nOld > 0 );
- Debug.Assert( nNew > 0 );
- if ( ( pageFlags & PTF_LEAF ) == 0 )
- {
- Buffer.BlockCopy( apCopy[nOld - 1].aData, 8, apNew[nNew - 1].aData, 8, 4 ); //u8* zChild = &apCopy[nOld - 1].aData[8];
- //memcpy( apNew[nNew - 1].aData[8], zChild, 4 );
- }
-
- if ( isRoot != 0 && pParent.nCell == 0 && pParent.hdrOffset <= apNew[0].nFree )
- {
- /* The root page of the b-tree now contains no cells. The only sibling
- ** page is the right-child of the parent. Copy the contents of the
- ** child page into the parent, decreasing the overall height of the
- ** b-tree structure by one. This is described as the "balance-shallower"
- ** sub-algorithm in some documentation.
- **
- ** If this is an auto-vacuum database, the call to copyNodeContent()
- ** sets all pointer-map entries corresponding to database image pages
- ** for which the pointer is stored within the content being copied.
- **
- ** The second Debug.Assert below verifies that the child page is defragmented
- ** (it must be, as it was just reconstructed using assemblePage()). This
- ** is important if the parent page happens to be page 1 of the database
- ** image. */
- Debug.Assert( nNew == 1 );
- Debug.Assert( apNew[0].nFree ==
- ( get2byte( apNew[0].aData, 5 ) - apNew[0].cellOffset - apNew[0].nCell * 2 )
- );
- copyNodeContent( apNew[0], pParent, ref rc );
- freePage( apNew[0], ref rc );
- }
- else
+ {
+ ptrmapPut(pBt, pNew.pgno, PTRMAP_BTREE, pParent.pgno, ref rc);
+ if (rc != SQLITE_OK) {
+ goto balance_cleanup;
+ }
+ }
+ }
+ }
+
+ /* Free any old pages that were not reused as new pages.
+ */
+ while (i < nOld) {
+ freePage(apOld[i], ref rc);
+ if (rc != 0)
+ goto balance_cleanup;
+ releasePage(apOld[i]);
+ apOld[i] = null;
+ i++;
+ }
+
+ /*
+ ** Put the new pages in accending order. This helps to
+ ** keep entries in the disk file in order so that a scan
+ ** of the table is a linear scan through the file. That
+ ** in turn helps the operating system to deliver pages
+ ** from the disk more rapidly.
+ **
+ ** An O(n^2) insertion sort algorithm is used, but since
+ ** n is never more than NB (a small constant), that should
+ ** not be a problem.
+ **
+ ** When NB==3, this one optimization makes the database
+ ** about 25% faster for large insertions and deletions.
+ */
+ for (i = 0; i < k - 1; i++) {
+ int minV = (int)apNew[i].pgno;
+ int minI = i;
+ for (j = i + 1; j < k; j++) {
+ if (apNew[j].pgno < (u32)minV) {
+ minI = j;
+ minV = (int)apNew[j].pgno;
+ }
+ }
+ if (minI > i) {
+ MemPage pT;
+ pT = apNew[i];
+ apNew[i] = apNew[minI];
+ apNew[minI] = pT;
+ }
+ }
+ TRACE("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
+ apNew[0].pgno, szNew[0],
+ nNew >= 2 ? apNew[1].pgno : 0, nNew >= 2 ? szNew[1] : 0,
+ nNew >= 3 ? apNew[2].pgno : 0, nNew >= 3 ? szNew[2] : 0,
+ nNew >= 4 ? apNew[3].pgno : 0, nNew >= 4 ? szNew[3] : 0,
+ nNew >= 5 ? apNew[4].pgno : 0, nNew >= 5 ? szNew[4] : 0);
+
+ Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage));
+ sqlite3Put4byte(pParent.aData, pRight, apNew[nNew - 1].pgno);
+
+ /*
+ ** Evenly distribute the data in apCell[] across the new pages.
+ ** Insert divider cells into pParent as necessary.
+ */
+ j = 0;
+ for (i = 0; i < nNew; i++) {
+ /* Assemble the new sibling page. */
+ MemPage pNew = apNew[i];
+ Debug.Assert(j < nMaxCells);
+ zeroPage(pNew, pageFlags);
+ assemblePage(pNew, cntNew[i] - j, apCell, szCell, j);
+ Debug.Assert(pNew.nCell > 0 || (nNew == 1 && cntNew[0] == 0));
+ Debug.Assert(pNew.nOverflow == 0);
+
+ j = cntNew[i];
+
+ /* If the sibling page assembled above was not the right-most sibling,
+ ** insert a divider cell into the parent page.
+ */
+ Debug.Assert(i < nNew - 1 || j == nCell);
+ if (j < nCell) {
+ u8[] pCell;
+ u8[] pTemp;
+ int sz;
+
+ Debug.Assert(j < nMaxCells);
+ pCell = apCell[j];
+ sz = szCell[j] + leafCorrection;
+ pTemp = sqlite3Malloc(sz);//&aOvflSpace[iOvflSpace];
+ if (0 == pNew.leaf) {
+ Buffer.BlockCopy(pCell, 0, pNew.aData, 8, 4);//memcpy( pNew.aData[8], pCell, 4 );
+ } else if (leafData != 0) {
+ /* If the tree is a leaf-data tree, and the siblings are leaves,
+ ** then there is no divider cell in apCell[]. Instead, the divider
+ ** cell consists of the integer key for the right-most cell of
+ ** the sibling-page assembled above only.
+ */
+ CellInfo info = new CellInfo();
+ j--;
+ btreeParseCellPtr(pNew, apCell[j], ref info);
+ pCell = pTemp;
+ sz = 4 + putVarint(pCell, 4, (u64)info.nKey);
+ pTemp = null;
+ } else {
+ //------------ pCell -= 4;
+ byte[] _pCell_4 = sqlite3Malloc(pCell.Length + 4);
+ Buffer.BlockCopy(pCell, 0, _pCell_4, 4, pCell.Length);
+ pCell = _pCell_4;
+ //
+ /* Obscure case for non-leaf-data trees: If the cell at pCell was
+ ** previously stored on a leaf node, and its reported size was 4
+ ** bytes, then it may actually be smaller than this
+ ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
+ ** any cell). But it is important to pass the correct size to
+ ** insertCell(), so reparse the cell now.
+ **
+ ** Note that this can never happen in an SQLite data file, as all
+ ** cells are at least 4 bytes. It only happens in b-trees used
+ ** to evaluate "IN (SELECT ...)" and similar clauses.
+ */
+ if (szCell[j] == 4) {
+ Debug.Assert(leafCorrection == 4);
+ sz = cellSizePtr(pParent, pCell);
+ }
+ }
+ iOvflSpace += sz;
+ Debug.Assert(sz <= pBt.maxLocal + 23);
+ Debug.Assert(iOvflSpace <= (int)pBt.pageSize);
+ insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew.pgno, ref rc);
+ if (rc != SQLITE_OK)
+ goto balance_cleanup;
+ Debug.Assert(sqlite3PagerIswriteable(pParent.pDbPage));
+
+ j++;
+ nxDiv++;
+ }
+ }
+ Debug.Assert(j == nCell);
+ Debug.Assert(nOld > 0);
+ Debug.Assert(nNew > 0);
+ if ((pageFlags & PTF_LEAF) == 0) {
+ Buffer.BlockCopy(apCopy[nOld - 1].aData, 8, apNew[nNew - 1].aData, 8, 4); //u8* zChild = &apCopy[nOld - 1].aData[8];
+ //memcpy( apNew[nNew - 1].aData[8], zChild, 4 );
+ }
+
+ if (isRoot != 0 && pParent.nCell == 0 && pParent.hdrOffset <= apNew[0].nFree) {
+ /* The root page of the b-tree now contains no cells. The only sibling
+ ** page is the right-child of the parent. Copy the contents of the
+ ** child page into the parent, decreasing the overall height of the
+ ** b-tree structure by one. This is described as the "balance-shallower"
+ ** sub-algorithm in some documentation.
+ **
+ ** If this is an auto-vacuum database, the call to copyNodeContent()
+ ** sets all pointer-map entries corresponding to database image pages
+ ** for which the pointer is stored within the content being copied.
+ **
+ ** The second Debug.Assert below verifies that the child page is defragmented
+ ** (it must be, as it was just reconstructed using assemblePage()). This
+ ** is important if the parent page happens to be page 1 of the database
+ ** image. */
+ Debug.Assert(nNew == 1);
+ Debug.Assert(apNew[0].nFree ==
+ (get2byte(apNew[0].aData, 5) - apNew[0].cellOffset - apNew[0].nCell * 2)
+ );
+ copyNodeContent(apNew[0], pParent, ref rc);
+ freePage(apNew[0], ref rc);
+ } else
#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM )
- if ( pBt.autoVacuum )
+ if (pBt.autoVacuum)
#else
if (false)
#endif
- {
- /* Fix the pointer-map entries for all the cells that were shifted around.
- ** There are several different types of pointer-map entries that need to
- ** be dealt with by this routine. Some of these have been set already, but
- ** many have not. The following is a summary:
- **
- ** 1) The entries associated with new sibling pages that were not
- ** siblings when this function was called. These have already
- ** been set. We don't need to worry about old siblings that were
- ** moved to the free-list - the freePage() code has taken care
- ** of those.
- **
- ** 2) The pointer-map entries associated with the first overflow
- ** page in any overflow chains used by new divider cells. These
- ** have also already been taken care of by the insertCell() code.
- **
- ** 3) If the sibling pages are not leaves, then the child pages of
- ** cells stored on the sibling pages may need to be updated.
- **
- ** 4) If the sibling pages are not internal intkey nodes, then any
- ** overflow pages used by these cells may need to be updated
- ** (internal intkey nodes never contain pointers to overflow pages).
- **
- ** 5) If the sibling pages are not leaves, then the pointer-map
- ** entries for the right-child pages of each sibling may need
- ** to be updated.
- **
- ** Cases 1 and 2 are dealt with above by other code. The next
- ** block deals with cases 3 and 4 and the one after that, case 5. Since
- ** setting a pointer map entry is a relatively expensive operation, this
- ** code only sets pointer map entries for child or overflow pages that have
- ** actually moved between pages. */
- MemPage pNew = apNew[0];
- MemPage pOld = apCopy[0];
- int nOverflow = pOld.nOverflow;
- int iNextOld = pOld.nCell + nOverflow;
- int iOverflow = ( nOverflow != 0 ? pOld.aOvfl[0].idx : -1 );
- j = 0; /* Current 'old' sibling page */
- k = 0; /* Current 'new' sibling page */
- for ( i = 0; i < nCell; i++ )
- {
- int isDivider = 0;
- while ( i == iNextOld )
- {
- /* Cell i is the cell immediately following the last cell on old
- ** sibling page j. If the siblings are not leaf pages of an
- ** intkey b-tree, then cell i was a divider cell. */
- pOld = apCopy[++j];
- iNextOld = i + ( 0 == leafData ? 1 : 0 ) + pOld.nCell + pOld.nOverflow;
- if ( pOld.nOverflow != 0 )
- {
- nOverflow = pOld.nOverflow;
- iOverflow = i + ( 0 == leafData ? 1 : 0 ) + pOld.aOvfl[0].idx;
- }
- isDivider = 0 == leafData ? 1 : 0;
- }
-
- Debug.Assert( nOverflow > 0 || iOverflow < i );
- Debug.Assert( nOverflow < 2 || pOld.aOvfl[0].idx == pOld.aOvfl[1].idx - 1 );
- Debug.Assert( nOverflow < 3 || pOld.aOvfl[1].idx == pOld.aOvfl[2].idx - 1 );
- if ( i == iOverflow )
- {
- isDivider = 1;
- if ( ( --nOverflow ) > 0 )
- {
- iOverflow++;
- }
- }
-
- if ( i == cntNew[k] )
- {
- /* Cell i is the cell immediately following the last cell on new
- ** sibling page k. If the siblings are not leaf pages of an
- ** intkey b-tree, then cell i is a divider cell. */
- pNew = apNew[++k];
- if ( 0 == leafData )
- continue;
- }
- Debug.Assert( j < nOld );
- Debug.Assert( k < nNew );
-
- /* If the cell was originally divider cell (and is not now) or
- ** an overflow cell, or if the cell was located on a different sibling
- ** page before the balancing, then the pointer map entries associated
- ** with any child or overflow pages need to be updated. */
- if ( isDivider != 0 || pOld.pgno != pNew.pgno )
- {
- if ( 0 == leafCorrection )
- {
- ptrmapPut( pBt, sqlite3Get4byte( apCell[i] ), PTRMAP_BTREE, pNew.pgno, ref rc );
- }
- if ( szCell[i] > pNew.minLocal )
- {
- ptrmapPutOvflPtr( pNew, apCell[i], ref rc );
- }
- }
- }
-
- if ( 0 == leafCorrection )
- {
- for ( i = 0; i < nNew; i++ )
- {
- u32 key = sqlite3Get4byte( apNew[i].aData, 8 );
- ptrmapPut( pBt, key, PTRMAP_BTREE, apNew[i].pgno, ref rc );
- }
- }
+ {
+ /* Fix the pointer-map entries for all the cells that were shifted around.
+ ** There are several different types of pointer-map entries that need to
+ ** be dealt with by this routine. Some of these have been set already, but
+ ** many have not. The following is a summary:
+ **
+ ** 1) The entries associated with new sibling pages that were not
+ ** siblings when this function was called. These have already
+ ** been set. We don't need to worry about old siblings that were
+ ** moved to the free-list - the freePage() code has taken care
+ ** of those.
+ **
+ ** 2) The pointer-map entries associated with the first overflow
+ ** page in any overflow chains used by new divider cells. These
+ ** have also already been taken care of by the insertCell() code.
+ **
+ ** 3) If the sibling pages are not leaves, then the child pages of
+ ** cells stored on the sibling pages may need to be updated.
+ **
+ ** 4) If the sibling pages are not internal intkey nodes, then any
+ ** overflow pages used by these cells may need to be updated
+ ** (internal intkey nodes never contain pointers to overflow pages).
+ **
+ ** 5) If the sibling pages are not leaves, then the pointer-map
+ ** entries for the right-child pages of each sibling may need
+ ** to be updated.
+ **
+ ** Cases 1 and 2 are dealt with above by other code. The next
+ ** block deals with cases 3 and 4 and the one after that, case 5. Since
+ ** setting a pointer map entry is a relatively expensive operation, this
+ ** code only sets pointer map entries for child or overflow pages that have
+ ** actually moved between pages. */
+ MemPage pNew = apNew[0];
+ MemPage pOld = apCopy[0];
+ int nOverflow = pOld.nOverflow;
+ int iNextOld = pOld.nCell + nOverflow;
+ int iOverflow = (nOverflow != 0 ? pOld.aOvfl[0].idx : -1);
+ j = 0; /* Current 'old' sibling page */
+ k = 0; /* Current 'new' sibling page */
+ for (i = 0; i < nCell; i++) {
+ int isDivider = 0;
+ while (i == iNextOld) {
+ /* Cell i is the cell immediately following the last cell on old
+ ** sibling page j. If the siblings are not leaf pages of an
+ ** intkey b-tree, then cell i was a divider cell. */
+ pOld = apCopy[++j];
+ iNextOld = i + (0 == leafData ? 1 : 0) + pOld.nCell + pOld.nOverflow;
+ if (pOld.nOverflow != 0) {
+ nOverflow = pOld.nOverflow;
+ iOverflow = i + (0 == leafData ? 1 : 0) + pOld.aOvfl[0].idx;
+ }
+ isDivider = 0 == leafData ? 1 : 0;
+ }
+
+ Debug.Assert(nOverflow > 0 || iOverflow < i);
+ Debug.Assert(nOverflow < 2 || pOld.aOvfl[0].idx == pOld.aOvfl[1].idx - 1);
+ Debug.Assert(nOverflow < 3 || pOld.aOvfl[1].idx == pOld.aOvfl[2].idx - 1);
+ if (i == iOverflow) {
+ isDivider = 1;
+ if ((--nOverflow) > 0) {
+ iOverflow++;
+ }
+ }
+
+ if (i == cntNew[k]) {
+ /* Cell i is the cell immediately following the last cell on new
+ ** sibling page k. If the siblings are not leaf pages of an
+ ** intkey b-tree, then cell i is a divider cell. */
+ pNew = apNew[++k];
+ if (0 == leafData)
+ continue;
+ }
+ Debug.Assert(j < nOld);
+ Debug.Assert(k < nNew);
+
+ /* If the cell was originally divider cell (and is not now) or
+ ** an overflow cell, or if the cell was located on a different sibling
+ ** page before the balancing, then the pointer map entries associated
+ ** with any child or overflow pages need to be updated. */
+ if (isDivider != 0 || pOld.pgno != pNew.pgno) {
+ if (0 == leafCorrection) {
+ ptrmapPut(pBt, sqlite3Get4byte(apCell[i]), PTRMAP_BTREE, pNew.pgno, ref rc);
+ }
+ if (szCell[i] > pNew.minLocal) {
+ ptrmapPutOvflPtr(pNew, apCell[i], ref rc);
+ }
+ }
+ }
+
+ if (0 == leafCorrection) {
+ for (i = 0; i < nNew; i++) {
+ u32 key = sqlite3Get4byte(apNew[i].aData, 8);
+ ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i].pgno, ref rc);
+ }
+ }
#if FALSE
/* The ptrmapCheckPages() contains Debug.Assert() statements that verify that
@@ -7549,579 +6860,539 @@ static int balance_nonroot(
ptrmapCheckPages(apNew, nNew);
ptrmapCheckPages(pParent, 1);
#endif
- }
+ }
- Debug.Assert( pParent.isInit != 0 );
- TRACE( "BALANCE: finished: old=%d new=%d cells=%d\n",
- nOld, nNew, nCell );
+ Debug.Assert(pParent.isInit != 0);
+ TRACE("BALANCE: finished: old=%d new=%d cells=%d\n",
+ nOld, nNew, nCell);
-/*
-** Cleanup before returning.
-*/
-balance_cleanup:
- sqlite3ScratchFree( apCell );
- for ( i = 0; i < nOld; i++ )
- {
- releasePage( apOld[i] );
- }
- for ( i = 0; i < nNew; i++ )
- {
- releasePage( apNew[i] );
- }
-
- return rc;
-}
+ /*
+ ** Cleanup before returning.
+ */
+ balance_cleanup:
+ sqlite3ScratchFree(apCell);
+ for (i = 0; i < nOld; i++) {
+ releasePage(apOld[i]);
+ }
+ for (i = 0; i < nNew; i++) {
+ releasePage(apNew[i]);
+ }
+
+ return rc;
+ }
-/*
-** This function is called when the root page of a b-tree structure is
-** overfull (has one or more overflow pages).
-**
-** A new child page is allocated and the contents of the current root
-** page, including overflow cells, are copied into the child. The root
-** page is then overwritten to make it an empty page with the right-child
-** pointer pointing to the new page.
-**
-** Before returning, all pointer-map entries corresponding to pages
-** that the new child-page now contains pointers to are updated. The
-** entry corresponding to the new right-child pointer of the root
-** page is also updated.
-**
-** If successful, ppChild is set to contain a reference to the child
-** page and SQLITE_OK is returned. In this case the caller is required
-** to call releasePage() on ppChild exactly once. If an error occurs,
-** an error code is returned and ppChild is set to 0.
-*/
-static int balance_deeper( MemPage pRoot, ref MemPage ppChild )
-{
- int rc; /* Return value from subprocedures */
- MemPage pChild = null; /* Pointer to a new child page */
- Pgno pgnoChild = 0; /* Page number of the new child page */
- BtShared pBt = pRoot.pBt; /* The BTree */
-
- Debug.Assert( pRoot.nOverflow > 0 );
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
-
- /* Make pRoot, the root page of the b-tree, writable. Allocate a new
- ** page that will become the new right-child of pPage. Copy the contents
- ** of the node stored on pRoot into the new child page.
- */
- rc = sqlite3PagerWrite( pRoot.pDbPage );
- if ( rc == SQLITE_OK )
- {
- rc = allocateBtreePage( pBt, ref pChild, ref pgnoChild, pRoot.pgno, 0 );
- copyNodeContent( pRoot, pChild, ref rc );
+ /*
+ ** This function is called when the root page of a b-tree structure is
+ ** overfull (has one or more overflow pages).
+ **
+ ** A new child page is allocated and the contents of the current root
+ ** page, including overflow cells, are copied into the child. The root
+ ** page is then overwritten to make it an empty page with the right-child
+ ** pointer pointing to the new page.
+ **
+ ** Before returning, all pointer-map entries corresponding to pages
+ ** that the new child-page now contains pointers to are updated. The
+ ** entry corresponding to the new right-child pointer of the root
+ ** page is also updated.
+ **
+ ** If successful, ppChild is set to contain a reference to the child
+ ** page and SQLITE_OK is returned. In this case the caller is required
+ ** to call releasePage() on ppChild exactly once. If an error occurs,
+ ** an error code is returned and ppChild is set to 0.
+ */
+ static int balance_deeper(MemPage pRoot, ref MemPage ppChild) {
+ int rc; /* Return value from subprocedures */
+ MemPage pChild = null; /* Pointer to a new child page */
+ Pgno pgnoChild = 0; /* Page number of the new child page */
+ BtShared pBt = pRoot.pBt; /* The BTree */
+
+ Debug.Assert(pRoot.nOverflow > 0);
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+
+ /* Make pRoot, the root page of the b-tree, writable. Allocate a new
+ ** page that will become the new right-child of pPage. Copy the contents
+ ** of the node stored on pRoot into the new child page.
+ */
+ rc = sqlite3PagerWrite(pRoot.pDbPage);
+ if (rc == SQLITE_OK) {
+ rc = allocateBtreePage(pBt, ref pChild, ref pgnoChild, pRoot.pgno, 0);
+ copyNodeContent(pRoot, pChild, ref rc);
#if !SQLITE_OMIT_AUTOVACUUM // if ( ISAUTOVACUUM )
- if ( pBt.autoVacuum )
+ if (pBt.autoVacuum)
#else
if (false)
#endif
- {
- ptrmapPut( pBt, pgnoChild, PTRMAP_BTREE, pRoot.pgno, ref rc );
- }
- }
- if ( rc != 0 )
- {
- ppChild = null;
- releasePage( pChild );
- return rc;
- }
- Debug.Assert( sqlite3PagerIswriteable( pChild.pDbPage ) );
- Debug.Assert( sqlite3PagerIswriteable( pRoot.pDbPage ) );
- Debug.Assert( pChild.nCell == pRoot.nCell );
-
- TRACE( "BALANCE: copy root %d into %d\n", pRoot.pgno, pChild.pgno );
-
- /* Copy the overflow cells from pRoot to pChild */
- Array.Copy( pRoot.aOvfl, pChild.aOvfl, pRoot.nOverflow );//memcpy(pChild.aOvfl, pRoot.aOvfl, pRoot.nOverflow*sizeof(pRoot.aOvfl[0]));
- pChild.nOverflow = pRoot.nOverflow;
-
- /* Zero the contents of pRoot. Then install pChild as the right-child. */
- zeroPage( pRoot, pChild.aData[0] & ~PTF_LEAF );
- sqlite3Put4byte( pRoot.aData, pRoot.hdrOffset + 8, pgnoChild );
-
- ppChild = pChild;
- return SQLITE_OK;
-}
+ {
+ ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot.pgno, ref rc);
+ }
+ }
+ if (rc != 0) {
+ ppChild = null;
+ releasePage(pChild);
+ return rc;
+ }
+ Debug.Assert(sqlite3PagerIswriteable(pChild.pDbPage));
+ Debug.Assert(sqlite3PagerIswriteable(pRoot.pDbPage));
+ Debug.Assert(pChild.nCell == pRoot.nCell);
-/*
-** The page that pCur currently points to has just been modified in
-** some way. This function figures out if this modification means the
-** tree needs to be balanced, and if so calls the appropriate balancing
-** routine. Balancing routines are:
-**
-** balance_quick()
-** balance_deeper()
-** balance_nonroot()
-*/
-static u8[] aBalanceQuickSpace = new u8[13];
-static int balance( BtCursor pCur )
-{
- int rc = SQLITE_OK;
- int nMin = (int)pCur.pBt.usableSize * 2 / 3;
+ TRACE("BALANCE: copy root %d into %d\n", pRoot.pgno, pChild.pgno);
+
+ /* Copy the overflow cells from pRoot to pChild */
+ Array.Copy(pRoot.aOvfl, pChild.aOvfl, pRoot.nOverflow);//memcpy(pChild.aOvfl, pRoot.aOvfl, pRoot.nOverflow*sizeof(pRoot.aOvfl[0]));
+ pChild.nOverflow = pRoot.nOverflow;
+
+ /* Zero the contents of pRoot. Then install pChild as the right-child. */
+ zeroPage(pRoot, pChild.aData[0] & ~PTF_LEAF);
+ sqlite3Put4byte(pRoot.aData, pRoot.hdrOffset + 8, pgnoChild);
+
+ ppChild = pChild;
+ return SQLITE_OK;
+ }
- //u8[] pFree = null;
+ /*
+ ** The page that pCur currently points to has just been modified in
+ ** some way. This function figures out if this modification means the
+ ** tree needs to be balanced, and if so calls the appropriate balancing
+ ** routine. Balancing routines are:
+ **
+ ** balance_quick()
+ ** balance_deeper()
+ ** balance_nonroot()
+ */
+ static u8[] aBalanceQuickSpace = new u8[13];
+ static int balance(BtCursor pCur) {
+ int rc = SQLITE_OK;
+ int nMin = (int)pCur.pBt.usableSize * 2 / 3;
+
+ //u8[] pFree = null;
#if !NDEBUG || SQLITE_COVERAGE_TEST || DEBUG
- int balance_quick_called = 0;//TESTONLY( int balance_quick_called = 0 );
- int balance_deeper_called = 0;//TESTONLY( int balance_deeper_called = 0 );
+ int balance_quick_called = 0;//TESTONLY( int balance_quick_called = 0 );
+ int balance_deeper_called = 0;//TESTONLY( int balance_deeper_called = 0 );
#else
int balance_quick_called = 0;
int balance_deeper_called = 0;
#endif
- do
- {
- int iPage = pCur.iPage;
- MemPage pPage = pCur.apPage[iPage];
+ do {
+ int iPage = pCur.iPage;
+ MemPage pPage = pCur.apPage[iPage];
+
+ if (iPage == 0) {
+ if (pPage.nOverflow != 0) {
+ /* The root page of the b-tree is overfull. In this case call the
+ ** balance_deeper() function to create a new child for the root-page
+ ** and copy the current contents of the root-page to it. The
+ ** next iteration of the do-loop will balance the child page.
+ */
+ Debug.Assert((balance_deeper_called++) == 0);
+ rc = balance_deeper(pPage, ref pCur.apPage[1]);
+ if (rc == SQLITE_OK) {
+ pCur.iPage = 1;
+ pCur.aiIdx[0] = 0;
+ pCur.aiIdx[1] = 0;
+ Debug.Assert(pCur.apPage[1].nOverflow != 0);
+ }
+ } else {
+ break;
+ }
+ } else if (pPage.nOverflow == 0 && pPage.nFree <= nMin) {
+ break;
+ } else {
+ MemPage pParent = pCur.apPage[iPage - 1];
+ int iIdx = pCur.aiIdx[iPage - 1];
+
+ rc = sqlite3PagerWrite(pParent.pDbPage);
+ if (rc == SQLITE_OK) {
+#if !SQLITE_OMIT_QUICKBALANCE
+ if (pPage.hasData != 0
+ && pPage.nOverflow == 1
+ && pPage.aOvfl[0].idx == pPage.nCell
+ && pParent.pgno != 1
+ && pParent.nCell == iIdx
+ ) {
+ /* Call balance_quick() to create a new sibling of pPage on which
+ ** to store the overflow cell. balance_quick() inserts a new cell
+ ** into pParent, which may cause pParent overflow. If this
+ ** happens, the next interation of the do-loop will balance pParent
+ ** use either balance_nonroot() or balance_deeper(). Until this
+ ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
+ ** buffer.
+ **
+ ** The purpose of the following Debug.Assert() is to check that only a
+ ** single call to balance_quick() is made for each call to this
+ ** function. If this were not verified, a subtle bug involving reuse
+ ** of the aBalanceQuickSpace[] might sneak in.
+ */
+ Debug.Assert((balance_quick_called++) == 0);
+ rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
+ } else
+#endif
+ {
+ /* In this case, call balance_nonroot() to redistribute cells
+ ** between pPage and up to 2 of its sibling pages. This involves
+ ** modifying the contents of pParent, which may cause pParent to
+ ** become overfull or underfull. The next iteration of the do-loop
+ ** will balance the parent page to correct this.
+ **
+ ** If the parent page becomes overfull, the overflow cell or cells
+ ** are stored in the pSpace buffer allocated immediately below.
+ ** A subsequent iteration of the do-loop will deal with this by
+ ** calling balance_nonroot() (balance_deeper() may be called first,
+ ** but it doesn't deal with overflow cells - just moves them to a
+ ** different page). Once this subsequent call to balance_nonroot()
+ ** has completed, it is safe to release the pSpace buffer used by
+ ** the previous call, as the overflow cell data will have been
+ ** copied either into the body of a database page or into the new
+ ** pSpace buffer passed to the latter call to balance_nonroot().
+ */
+ ////u8[] pSpace = new u8[pCur.pBt.pageSize];// u8 pSpace = sqlite3PageMalloc( pCur.pBt.pageSize );
+ rc = balance_nonroot(pParent, iIdx, null, iPage == 1 ? 1 : 0);
+ //if (pFree != null)
+ //{
+ // /* If pFree is not NULL, it points to the pSpace buffer used
+ // ** by a previous call to balance_nonroot(). Its contents are
+ // ** now stored either on real database pages or within the
+ // ** new pSpace buffer, so it may be safely freed here. */
+ // sqlite3PageFree(ref pFree);
+ //}
+
+ /* The pSpace buffer will be freed after the next call to
+ ** balance_nonroot(), or just before this function returns, whichever
+ ** comes first. */
+ //pFree = pSpace;
+ }
+ }
+
+ pPage.nOverflow = 0;
+
+ /* The next iteration of the do-loop balances the parent page. */
+ releasePage(pPage);
+ pCur.iPage--;
+ }
+ } while (rc == SQLITE_OK);
+
+ //if (pFree != null)
+ //{
+ // sqlite3PageFree(ref pFree);
+ //}
+ return rc;
+ }
- if ( iPage == 0 )
- {
- if ( pPage.nOverflow != 0 )
- {
- /* The root page of the b-tree is overfull. In this case call the
- ** balance_deeper() function to create a new child for the root-page
- ** and copy the current contents of the root-page to it. The
- ** next iteration of the do-loop will balance the child page.
- */
- Debug.Assert( ( balance_deeper_called++ ) == 0 );
- rc = balance_deeper( pPage, ref pCur.apPage[1] );
- if ( rc == SQLITE_OK )
- {
- pCur.iPage = 1;
- pCur.aiIdx[0] = 0;
- pCur.aiIdx[1] = 0;
- Debug.Assert( pCur.apPage[1].nOverflow != 0 );
- }
- }
- else
- {
- break;
- }
- }
- else if ( pPage.nOverflow == 0 && pPage.nFree <= nMin )
- {
- break;
- }
- else
- {
- MemPage pParent = pCur.apPage[iPage - 1];
- int iIdx = pCur.aiIdx[iPage - 1];
- rc = sqlite3PagerWrite( pParent.pDbPage );
- if ( rc == SQLITE_OK )
- {
-#if !SQLITE_OMIT_QUICKBALANCE
- if ( pPage.hasData != 0
- && pPage.nOverflow == 1
- && pPage.aOvfl[0].idx == pPage.nCell
- && pParent.pgno != 1
- && pParent.nCell == iIdx
- )
- {
- /* Call balance_quick() to create a new sibling of pPage on which
- ** to store the overflow cell. balance_quick() inserts a new cell
- ** into pParent, which may cause pParent overflow. If this
- ** happens, the next interation of the do-loop will balance pParent
- ** use either balance_nonroot() or balance_deeper(). Until this
- ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
- ** buffer.
- **
- ** The purpose of the following Debug.Assert() is to check that only a
- ** single call to balance_quick() is made for each call to this
- ** function. If this were not verified, a subtle bug involving reuse
- ** of the aBalanceQuickSpace[] might sneak in.
- */
- Debug.Assert( ( balance_quick_called++ ) == 0 );
- rc = balance_quick( pParent, pPage, aBalanceQuickSpace );
+ /*
+ ** Insert a new record into the BTree. The key is given by (pKey,nKey)
+ ** and the data is given by (pData,nData). The cursor is used only to
+ ** define what table the record should be inserted into. The cursor
+ ** is left pointing at a random location.
+ **
+ ** For an INTKEY table, only the nKey value of the key is used. pKey is
+ ** ignored. For a ZERODATA table, the pData and nData are both ignored.
+ **
+ ** If the seekResult parameter is non-zero, then a successful call to
+ ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
+ ** been performed. seekResult is the search result returned (a negative
+ ** number if pCur points at an entry that is smaller than (pKey, nKey), or
+ ** a positive value if pCur points at an etry that is larger than
+ ** (pKey, nKey)).
+ **
+ ** If the seekResult parameter is non-zero, then the caller guarantees that
+ ** cursor pCur is pointing at the existing copy of a row that is to be
+ ** overwritten. If the seekResult parameter is 0, then cursor pCur may
+ ** point to any entry or to no entry at all and so this function has to seek
+ ** the cursor before the new key can be inserted.
+ */
+ static int sqlite3BtreeInsert(
+ BtCursor pCur, /* Insert data into the table of this cursor */
+ byte[] pKey, i64 nKey, /* The key of the new record */
+ byte[] pData, int nData, /* The data of the new record */
+ int nZero, /* Number of extra 0 bytes to append to data */
+ int appendBias, /* True if this is likely an append */
+ int seekResult /* Result of prior MovetoUnpacked() call */
+ ) {
+ int rc;
+ int loc = seekResult; /* -1: before desired location +1: after */
+ int szNew = 0;
+ int idx;
+ MemPage pPage;
+ Btree p = pCur.pBtree;
+ BtShared pBt = p.pBt;
+ int oldCell;
+ byte[] newCell = null;
+
+ if (pCur.eState == CURSOR_FAULT) {
+ Debug.Assert(pCur.skipNext != SQLITE_OK);
+ return pCur.skipNext;
+ }
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pCur.wrFlag != 0 && pBt.inTransaction == TRANS_WRITE && !pBt.readOnly);
+ Debug.Assert(hasSharedCacheTableLock(p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2));
+
+ /* Assert that the caller has been consistent. If this cursor was opened
+ ** expecting an index b-tree, then the caller should be inserting blob
+ ** keys with no associated data. If the cursor was opened expecting an
+ ** intkey table, the caller should be inserting integer keys with a
+ ** blob of associated data. */
+ Debug.Assert((pKey == null) == (pCur.pKeyInfo == null));
+
+ /* If this is an insert into a table b-tree, invalidate any incrblob
+ ** cursors open on the row being replaced (assuming this is a replace
+ ** operation - if it is not, the following is a no-op). */
+ if (pCur.pKeyInfo == null) {
+ invalidateIncrblobCursors(p, nKey, 0);
+ }
+
+ /* Save the positions of any other cursors open on this table.
+ **
+ ** In some cases, the call to btreeMoveto() below is a no-op. For
+ ** example, when inserting data into a table with auto-generated integer
+ ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
+ ** integer key to use. It then calls this function to actually insert the
+ ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
+ ** that the cursor is already where it needs to be and returns without
+ ** doing any work. To avoid thwarting these optimizations, it is important
+ ** not to clear the cursor here.
+ */
+ rc = saveAllCursors(pBt, pCur.pgnoRoot, pCur);
+ if (rc != 0)
+ return rc;
+ if (0 == loc) {
+ rc = btreeMoveto(pCur, pKey, nKey, appendBias, ref loc);
+ if (rc != 0)
+ return rc;
+ }
+ Debug.Assert(pCur.eState == CURSOR_VALID || (pCur.eState == CURSOR_INVALID && loc != 0));
+
+ pPage = pCur.apPage[pCur.iPage];
+ Debug.Assert(pPage.intKey != 0 || nKey >= 0);
+ Debug.Assert(pPage.leaf != 0 || 0 == pPage.intKey);
+
+ TRACE("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
+ pCur.pgnoRoot, nKey, nData, pPage.pgno,
+ loc == 0 ? "overwrite" : "new entry");
+ Debug.Assert(pPage.isInit != 0);
+ allocateTempSpace(pBt);
+ newCell = pBt.pTmpSpace;
+ //if (newCell == null) return SQLITE_NOMEM;
+ rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, ref szNew);
+ if (rc != 0)
+ goto end_insert;
+ Debug.Assert(szNew == cellSizePtr(pPage, newCell));
+ Debug.Assert(szNew <= MX_CELL_SIZE(pBt));
+ idx = pCur.aiIdx[pCur.iPage];
+ if (loc == 0) {
+ u16 szOld;
+ Debug.Assert(idx < pPage.nCell);
+ rc = sqlite3PagerWrite(pPage.pDbPage);
+ if (rc != 0) {
+ goto end_insert;
+ }
+ oldCell = findCell(pPage, idx);
+ if (0 == pPage.leaf) {
+ //memcpy(newCell, oldCell, 4);
+ newCell[0] = pPage.aData[oldCell + 0];
+ newCell[1] = pPage.aData[oldCell + 1];
+ newCell[2] = pPage.aData[oldCell + 2];
+ newCell[3] = pPage.aData[oldCell + 3];
+ }
+ szOld = cellSizePtr(pPage, oldCell);
+ rc = clearCell(pPage, oldCell);
+ dropCell(pPage, idx, szOld, ref rc);
+ if (rc != 0)
+ goto end_insert;
+ } else if (loc < 0 && pPage.nCell > 0) {
+ Debug.Assert(pPage.leaf != 0);
+ idx = ++pCur.aiIdx[pCur.iPage];
+ } else {
+ Debug.Assert(pPage.leaf != 0);
+ }
+ insertCell(pPage, idx, newCell, szNew, null, 0, ref rc);
+ Debug.Assert(rc != SQLITE_OK || pPage.nCell > 0 || pPage.nOverflow > 0);
+
+ /* If no error has occured and pPage has an overflow cell, call balance()
+ ** to redistribute the cells within the tree. Since balance() may move
+ ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
+ ** variables.
+ **
+ ** Previous versions of SQLite called moveToRoot() to move the cursor
+ ** back to the root page as balance() used to invalidate the contents
+ ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
+ ** set the cursor state to "invalid". This makes common insert operations
+ ** slightly faster.
+ **
+ ** There is a subtle but important optimization here too. When inserting
+ ** multiple records into an intkey b-tree using a single cursor (as can
+ ** happen while processing an "INSERT INTO ... SELECT" statement), it
+ ** is advantageous to leave the cursor pointing to the last entry in
+ ** the b-tree if possible. If the cursor is left pointing to the last
+ ** entry in the table, and the next row inserted has an integer key
+ ** larger than the largest existing key, it is possible to insert the
+ ** row without seeking the cursor. This can be a big performance boost.
+ */
+ pCur.info.nSize = 0;
+ pCur.validNKey = false;
+ if (rc == SQLITE_OK && pPage.nOverflow != 0) {
+ rc = balance(pCur);
+
+ /* Must make sure nOverflow is reset to zero even if the balance()
+ ** fails. Internal data structure corruption will result otherwise.
+ ** Also, set the cursor state to invalid. This stops saveCursorPosition()
+ ** from trying to save the current position of the cursor. */
+ pCur.apPage[pCur.iPage].nOverflow = 0;
+ pCur.eState = CURSOR_INVALID;
+ }
+ Debug.Assert(pCur.apPage[pCur.iPage].nOverflow == 0);
+
+ end_insert:
+ return rc;
}
- else
-#endif
- {
- /* In this case, call balance_nonroot() to redistribute cells
- ** between pPage and up to 2 of its sibling pages. This involves
- ** modifying the contents of pParent, which may cause pParent to
- ** become overfull or underfull. The next iteration of the do-loop
- ** will balance the parent page to correct this.
- **
- ** If the parent page becomes overfull, the overflow cell or cells
- ** are stored in the pSpace buffer allocated immediately below.
- ** A subsequent iteration of the do-loop will deal with this by
- ** calling balance_nonroot() (balance_deeper() may be called first,
- ** but it doesn't deal with overflow cells - just moves them to a
- ** different page). Once this subsequent call to balance_nonroot()
- ** has completed, it is safe to release the pSpace buffer used by
- ** the previous call, as the overflow cell data will have been
- ** copied either into the body of a database page or into the new
- ** pSpace buffer passed to the latter call to balance_nonroot().
- */
- ////u8[] pSpace = new u8[pCur.pBt.pageSize];// u8 pSpace = sqlite3PageMalloc( pCur.pBt.pageSize );
- rc = balance_nonroot( pParent, iIdx, null, iPage == 1 ? 1 : 0 );
- //if (pFree != null)
- //{
- // /* If pFree is not NULL, it points to the pSpace buffer used
- // ** by a previous call to balance_nonroot(). Its contents are
- // ** now stored either on real database pages or within the
- // ** new pSpace buffer, so it may be safely freed here. */
- // sqlite3PageFree(ref pFree);
- //}
-
- /* The pSpace buffer will be freed after the next call to
- ** balance_nonroot(), or just before this function returns, whichever
- ** comes first. */
- //pFree = pSpace;
- }
- }
-
- pPage.nOverflow = 0;
-
- /* The next iteration of the do-loop balances the parent page. */
- releasePage( pPage );
- pCur.iPage--;
- }
- } while ( rc == SQLITE_OK );
- //if (pFree != null)
- //{
- // sqlite3PageFree(ref pFree);
- //}
- return rc;
-}
+ /*
+ ** Delete the entry that the cursor is pointing to. The cursor
+ ** is left pointing at a arbitrary location.
+ */
+ static int sqlite3BtreeDelete(BtCursor pCur) {
+ Btree p = pCur.pBtree;
+ BtShared pBt = p.pBt;
+ int rc; /* Return code */
+ MemPage pPage; /* Page to delete cell from */
+ int pCell; /* Pointer to cell to delete */
+ int iCellIdx; /* Index of cell to delete */
+ int iCellDepth; /* Depth of node containing pCell */
+
+ Debug.Assert(cursorHoldsMutex(pCur));
+ Debug.Assert(pBt.inTransaction == TRANS_WRITE);
+ Debug.Assert(!pBt.readOnly);
+ Debug.Assert(pCur.wrFlag != 0);
+ Debug.Assert(hasSharedCacheTableLock(p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2));
+ Debug.Assert(!hasReadConflicts(p, pCur.pgnoRoot));
+
+ if (NEVER(pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell)
+ || NEVER(pCur.eState != CURSOR_VALID)
+ ) {
+ return SQLITE_ERROR; /* Something has gone awry. */
+ }
+
+ /* If this is a delete operation to remove a row from a table b-tree,
+ ** invalidate any incrblob cursors open on the row being deleted. */
+ if (pCur.pKeyInfo == null) {
+ invalidateIncrblobCursors(p, pCur.info.nKey, 0);
+ }
+ iCellDepth = pCur.iPage;
+ iCellIdx = pCur.aiIdx[iCellDepth];
+ pPage = pCur.apPage[iCellDepth];
+ pCell = findCell(pPage, iCellIdx);
+
+ /* If the page containing the entry to delete is not a leaf page, move
+ ** the cursor to the largest entry in the tree that is smaller than
+ ** the entry being deleted. This cell will replace the cell being deleted
+ ** from the internal node. The 'previous' entry is used for this instead
+ ** of the 'next' entry, as the previous entry is always a part of the
+ ** sub-tree headed by the child page of the cell being deleted. This makes
+ ** balancing the tree following the delete operation easier. */
+ if (0 == pPage.leaf) {
+ int notUsed = 0;
+ rc = sqlite3BtreePrevious(pCur, ref notUsed);
+ if (rc != 0)
+ return rc;
+ }
-/*
-** Insert a new record into the BTree. The key is given by (pKey,nKey)
-** and the data is given by (pData,nData). The cursor is used only to
-** define what table the record should be inserted into. The cursor
-** is left pointing at a random location.
-**
-** For an INTKEY table, only the nKey value of the key is used. pKey is
-** ignored. For a ZERODATA table, the pData and nData are both ignored.
-**
-** If the seekResult parameter is non-zero, then a successful call to
-** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
-** been performed. seekResult is the search result returned (a negative
-** number if pCur points at an entry that is smaller than (pKey, nKey), or
-** a positive value if pCur points at an etry that is larger than
-** (pKey, nKey)).
-**
-** If the seekResult parameter is non-zero, then the caller guarantees that
-** cursor pCur is pointing at the existing copy of a row that is to be
-** overwritten. If the seekResult parameter is 0, then cursor pCur may
-** point to any entry or to no entry at all and so this function has to seek
-** the cursor before the new key can be inserted.
-*/
-static int sqlite3BtreeInsert(
-BtCursor pCur, /* Insert data into the table of this cursor */
-byte[] pKey, i64 nKey, /* The key of the new record */
-byte[] pData, int nData, /* The data of the new record */
-int nZero, /* Number of extra 0 bytes to append to data */
-int appendBias, /* True if this is likely an append */
-int seekResult /* Result of prior MovetoUnpacked() call */
-)
-{
- int rc;
- int loc = seekResult; /* -1: before desired location +1: after */
- int szNew = 0;
- int idx;
- MemPage pPage;
- Btree p = pCur.pBtree;
- BtShared pBt = p.pBt;
- int oldCell;
- byte[] newCell = null;
-
- if ( pCur.eState == CURSOR_FAULT )
- {
- Debug.Assert( pCur.skipNext != SQLITE_OK );
- return pCur.skipNext;
- }
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pCur.wrFlag != 0 && pBt.inTransaction == TRANS_WRITE && !pBt.readOnly );
- Debug.Assert( hasSharedCacheTableLock( p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2 ) );
-
- /* Assert that the caller has been consistent. If this cursor was opened
- ** expecting an index b-tree, then the caller should be inserting blob
- ** keys with no associated data. If the cursor was opened expecting an
- ** intkey table, the caller should be inserting integer keys with a
- ** blob of associated data. */
- Debug.Assert( ( pKey == null ) == ( pCur.pKeyInfo == null ) );
-
- /* If this is an insert into a table b-tree, invalidate any incrblob
- ** cursors open on the row being replaced (assuming this is a replace
- ** operation - if it is not, the following is a no-op). */
- if ( pCur.pKeyInfo == null )
- {
- invalidateIncrblobCursors( p, nKey, 0 );
- }
-
- /* Save the positions of any other cursors open on this table.
- **
- ** In some cases, the call to btreeMoveto() below is a no-op. For
- ** example, when inserting data into a table with auto-generated integer
- ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
- ** integer key to use. It then calls this function to actually insert the
- ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
- ** that the cursor is already where it needs to be and returns without
- ** doing any work. To avoid thwarting these optimizations, it is important
- ** not to clear the cursor here.
- */
- rc = saveAllCursors( pBt, pCur.pgnoRoot, pCur );
- if ( rc != 0 )
- return rc;
- if ( 0 == loc )
- {
- rc = btreeMoveto( pCur, pKey, nKey, appendBias, ref loc );
- if ( rc != 0 )
- return rc;
- }
- Debug.Assert( pCur.eState == CURSOR_VALID || ( pCur.eState == CURSOR_INVALID && loc != 0 ) );
-
- pPage = pCur.apPage[pCur.iPage];
- Debug.Assert( pPage.intKey != 0 || nKey >= 0 );
- Debug.Assert( pPage.leaf != 0 || 0 == pPage.intKey );
-
- TRACE( "INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
- pCur.pgnoRoot, nKey, nData, pPage.pgno,
- loc == 0 ? "overwrite" : "new entry" );
- Debug.Assert( pPage.isInit != 0 );
- allocateTempSpace( pBt );
- newCell = pBt.pTmpSpace;
- //if (newCell == null) return SQLITE_NOMEM;
- rc = fillInCell( pPage, newCell, pKey, nKey, pData, nData, nZero, ref szNew );
- if ( rc != 0 )
- goto end_insert;
- Debug.Assert( szNew == cellSizePtr( pPage, newCell ) );
- Debug.Assert( szNew <= MX_CELL_SIZE( pBt ) );
- idx = pCur.aiIdx[pCur.iPage];
- if ( loc == 0 )
- {
- u16 szOld;
- Debug.Assert( idx < pPage.nCell );
- rc = sqlite3PagerWrite( pPage.pDbPage );
- if ( rc != 0 )
- {
- goto end_insert;
- }
- oldCell = findCell( pPage, idx );
- if ( 0 == pPage.leaf )
- {
- //memcpy(newCell, oldCell, 4);
- newCell[0] = pPage.aData[oldCell + 0];
- newCell[1] = pPage.aData[oldCell + 1];
- newCell[2] = pPage.aData[oldCell + 2];
- newCell[3] = pPage.aData[oldCell + 3];
- }
- szOld = cellSizePtr( pPage, oldCell );
- rc = clearCell( pPage, oldCell );
- dropCell( pPage, idx, szOld, ref rc );
- if ( rc != 0 )
- goto end_insert;
- }
- else if ( loc < 0 && pPage.nCell > 0 )
- {
- Debug.Assert( pPage.leaf != 0 );
- idx = ++pCur.aiIdx[pCur.iPage];
- }
- else
- {
- Debug.Assert( pPage.leaf != 0 );
- }
- insertCell( pPage, idx, newCell, szNew, null, 0, ref rc );
- Debug.Assert( rc != SQLITE_OK || pPage.nCell > 0 || pPage.nOverflow > 0 );
-
- /* If no error has occured and pPage has an overflow cell, call balance()
- ** to redistribute the cells within the tree. Since balance() may move
- ** the cursor, zero the BtCursor.info.nSize and BtCursor.validNKey
- ** variables.
- **
- ** Previous versions of SQLite called moveToRoot() to move the cursor
- ** back to the root page as balance() used to invalidate the contents
- ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
- ** set the cursor state to "invalid". This makes common insert operations
- ** slightly faster.
- **
- ** There is a subtle but important optimization here too. When inserting
- ** multiple records into an intkey b-tree using a single cursor (as can
- ** happen while processing an "INSERT INTO ... SELECT" statement), it
- ** is advantageous to leave the cursor pointing to the last entry in
- ** the b-tree if possible. If the cursor is left pointing to the last
- ** entry in the table, and the next row inserted has an integer key
- ** larger than the largest existing key, it is possible to insert the
- ** row without seeking the cursor. This can be a big performance boost.
- */
- pCur.info.nSize = 0;
- pCur.validNKey = false;
- if ( rc == SQLITE_OK && pPage.nOverflow != 0 )
- {
- rc = balance( pCur );
-
- /* Must make sure nOverflow is reset to zero even if the balance()
- ** fails. Internal data structure corruption will result otherwise.
- ** Also, set the cursor state to invalid. This stops saveCursorPosition()
- ** from trying to save the current position of the cursor. */
- pCur.apPage[pCur.iPage].nOverflow = 0;
- pCur.eState = CURSOR_INVALID;
- }
- Debug.Assert( pCur.apPage[pCur.iPage].nOverflow == 0 );
-
-end_insert:
- return rc;
-}
+ /* Save the positions of any other cursors open on this table before
+ ** making any modifications. Make the page containing the entry to be
+ ** deleted writable. Then free any overflow pages associated with the
+ ** entry and finally remove the cell itself from within the page.
+ */
+ rc = saveAllCursors(pBt, pCur.pgnoRoot, pCur);
+ if (rc != 0)
+ return rc;
+ rc = sqlite3PagerWrite(pPage.pDbPage);
+ if (rc != 0)
+ return rc;
+ rc = clearCell(pPage, pCell);
+ dropCell(pPage, iCellIdx, cellSizePtr(pPage, pCell), ref rc);
+ if (rc != 0)
+ return rc;
+
+ /* If the cell deleted was not located on a leaf page, then the cursor
+ ** is currently pointing to the largest entry in the sub-tree headed
+ ** by the child-page of the cell that was just deleted from an internal
+ ** node. The cell from the leaf node needs to be moved to the internal
+ ** node to replace the deleted cell. */
+ if (0 == pPage.leaf) {
+ MemPage pLeaf = pCur.apPage[pCur.iPage];
+ int nCell;
+ Pgno n = pCur.apPage[iCellDepth + 1].pgno;
+ //byte[] pTmp;
+
+ pCell = findCell(pLeaf, pLeaf.nCell - 1);
+ nCell = cellSizePtr(pLeaf, pCell);
+ Debug.Assert(MX_CELL_SIZE(pBt) >= nCell);
+
+ //allocateTempSpace(pBt);
+ //pTmp = pBt.pTmpSpace;
+
+ rc = sqlite3PagerWrite(pLeaf.pDbPage);
+ byte[] pNext_4 = sqlite3Malloc(nCell + 4);
+ Buffer.BlockCopy(pLeaf.aData, pCell - 4, pNext_4, 0, nCell + 4);
+ insertCell(pPage, iCellIdx, pNext_4, nCell + 4, null, n, ref rc); //insertCell( pPage, iCellIdx, pCell - 4, nCell + 4, pTmp, n, ref rc );
+ dropCell(pLeaf, pLeaf.nCell - 1, nCell, ref rc);
+ if (rc != 0)
+ return rc;
+ }
-/*
-** Delete the entry that the cursor is pointing to. The cursor
-** is left pointing at a arbitrary location.
-*/
-static int sqlite3BtreeDelete( BtCursor pCur )
-{
- Btree p = pCur.pBtree;
- BtShared pBt = p.pBt;
- int rc; /* Return code */
- MemPage pPage; /* Page to delete cell from */
- int pCell; /* Pointer to cell to delete */
- int iCellIdx; /* Index of cell to delete */
- int iCellDepth; /* Depth of node containing pCell */
-
- Debug.Assert( cursorHoldsMutex( pCur ) );
- Debug.Assert( pBt.inTransaction == TRANS_WRITE );
- Debug.Assert( !pBt.readOnly );
- Debug.Assert( pCur.wrFlag != 0 );
- Debug.Assert( hasSharedCacheTableLock( p, pCur.pgnoRoot, pCur.pKeyInfo != null ? 1 : 0, 2 ) );
- Debug.Assert( !hasReadConflicts( p, pCur.pgnoRoot ) );
-
- if ( NEVER( pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell )
- || NEVER( pCur.eState != CURSOR_VALID )
- )
- {
- return SQLITE_ERROR; /* Something has gone awry. */
- }
-
- /* If this is a delete operation to remove a row from a table b-tree,
- ** invalidate any incrblob cursors open on the row being deleted. */
- if ( pCur.pKeyInfo == null )
- {
- invalidateIncrblobCursors( p, pCur.info.nKey, 0 );
- }
-
- iCellDepth = pCur.iPage;
- iCellIdx = pCur.aiIdx[iCellDepth];
- pPage = pCur.apPage[iCellDepth];
- pCell = findCell( pPage, iCellIdx );
-
- /* If the page containing the entry to delete is not a leaf page, move
- ** the cursor to the largest entry in the tree that is smaller than
- ** the entry being deleted. This cell will replace the cell being deleted
- ** from the internal node. The 'previous' entry is used for this instead
- ** of the 'next' entry, as the previous entry is always a part of the
- ** sub-tree headed by the child page of the cell being deleted. This makes
- ** balancing the tree following the delete operation easier. */
- if ( 0 == pPage.leaf )
- {
- int notUsed = 0;
- rc = sqlite3BtreePrevious( pCur, ref notUsed );
- if ( rc != 0 )
- return rc;
- }
-
- /* Save the positions of any other cursors open on this table before
- ** making any modifications. Make the page containing the entry to be
- ** deleted writable. Then free any overflow pages associated with the
- ** entry and finally remove the cell itself from within the page.
- */
- rc = saveAllCursors( pBt, pCur.pgnoRoot, pCur );
- if ( rc != 0 )
- return rc;
- rc = sqlite3PagerWrite( pPage.pDbPage );
- if ( rc != 0 )
- return rc;
- rc = clearCell( pPage, pCell );
- dropCell( pPage, iCellIdx, cellSizePtr( pPage, pCell ), ref rc );
- if ( rc != 0 )
- return rc;
-
- /* If the cell deleted was not located on a leaf page, then the cursor
- ** is currently pointing to the largest entry in the sub-tree headed
- ** by the child-page of the cell that was just deleted from an internal
- ** node. The cell from the leaf node needs to be moved to the internal
- ** node to replace the deleted cell. */
- if ( 0 == pPage.leaf )
- {
- MemPage pLeaf = pCur.apPage[pCur.iPage];
- int nCell;
- Pgno n = pCur.apPage[iCellDepth + 1].pgno;
- //byte[] pTmp;
-
- pCell = findCell( pLeaf, pLeaf.nCell - 1 );
- nCell = cellSizePtr( pLeaf, pCell );
- Debug.Assert( MX_CELL_SIZE( pBt ) >= nCell );
-
- //allocateTempSpace(pBt);
- //pTmp = pBt.pTmpSpace;
-
- rc = sqlite3PagerWrite( pLeaf.pDbPage );
- byte[] pNext_4 = sqlite3Malloc( nCell + 4 );
- Buffer.BlockCopy( pLeaf.aData, pCell - 4, pNext_4, 0, nCell + 4 );
- insertCell( pPage, iCellIdx, pNext_4, nCell + 4, null, n, ref rc ); //insertCell( pPage, iCellIdx, pCell - 4, nCell + 4, pTmp, n, ref rc );
- dropCell( pLeaf, pLeaf.nCell - 1, nCell, ref rc );
- if ( rc != 0 )
- return rc;
- }
-
- /* Balance the tree. If the entry deleted was located on a leaf page,
- ** then the cursor still points to that page. In this case the first
- ** call to balance() repairs the tree, and the if(...) condition is
- ** never true.
- **
- ** Otherwise, if the entry deleted was on an internal node page, then
- ** pCur is pointing to the leaf page from which a cell was removed to
- ** replace the cell deleted from the internal node. This is slightly
- ** tricky as the leaf node may be underfull, and the internal node may
- ** be either under or overfull. In this case run the balancing algorithm
- ** on the leaf node first. If the balance proceeds far enough up the
- ** tree that we can be sure that any problem in the internal node has
- ** been corrected, so be it. Otherwise, after balancing the leaf node,
- ** walk the cursor up the tree to the internal node and balance it as
- ** well. */
- rc = balance( pCur );
- if ( rc == SQLITE_OK && pCur.iPage > iCellDepth )
- {
- while ( pCur.iPage > iCellDepth )
- {
- releasePage( pCur.apPage[pCur.iPage--] );
- }
- rc = balance( pCur );
- }
-
- if ( rc == SQLITE_OK )
- {
- moveToRoot( pCur );
- }
- return rc;
-}
+ /* Balance the tree. If the entry deleted was located on a leaf page,
+ ** then the cursor still points to that page. In this case the first
+ ** call to balance() repairs the tree, and the if(...) condition is
+ ** never true.
+ **
+ ** Otherwise, if the entry deleted was on an internal node page, then
+ ** pCur is pointing to the leaf page from which a cell was removed to
+ ** replace the cell deleted from the internal node. This is slightly
+ ** tricky as the leaf node may be underfull, and the internal node may
+ ** be either under or overfull. In this case run the balancing algorithm
+ ** on the leaf node first. If the balance proceeds far enough up the
+ ** tree that we can be sure that any problem in the internal node has
+ ** been corrected, so be it. Otherwise, after balancing the leaf node,
+ ** walk the cursor up the tree to the internal node and balance it as
+ ** well. */
+ rc = balance(pCur);
+ if (rc == SQLITE_OK && pCur.iPage > iCellDepth) {
+ while (pCur.iPage > iCellDepth) {
+ releasePage(pCur.apPage[pCur.iPage--]);
+ }
+ rc = balance(pCur);
+ }
-/*
-** Create a new BTree table. Write into piTable the page
-** number for the root page of the new table.
-**
-** The type of type is determined by the flags parameter. Only the
-** following values of flags are currently in use. Other values for
-** flags might not work:
-**
-** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
-** BTREE_ZERODATA Used for SQL indices
-*/
-static int btreeCreateTable( Btree p, ref int piTable, int createTabFlags )
-{
- BtShared pBt = p.pBt;
- MemPage pRoot = new MemPage();
- Pgno pgnoRoot = 0;
- int rc;
- int ptfFlags; /* Page-type flage for the root page of new table */
+ if (rc == SQLITE_OK) {
+ moveToRoot(pCur);
+ }
+ return rc;
+ }
+
+ /*
+ ** Create a new BTree table. Write into piTable the page
+ ** number for the root page of the new table.
+ **
+ ** The type of type is determined by the flags parameter. Only the
+ ** following values of flags are currently in use. Other values for
+ ** flags might not work:
+ **
+ ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
+ ** BTREE_ZERODATA Used for SQL indices
+ */
+ static int btreeCreateTable(Btree p, ref int piTable, int createTabFlags) {
+ BtShared pBt = p.pBt;
+ MemPage pRoot = new MemPage();
+ Pgno pgnoRoot = 0;
+ int rc;
+ int ptfFlags; /* Page-type flage for the root page of new table */
- Debug.Assert( sqlite3BtreeHoldsMutex( p ) );
- Debug.Assert( pBt.inTransaction == TRANS_WRITE );
- Debug.Assert( !pBt.readOnly );
+ Debug.Assert(sqlite3BtreeHoldsMutex(p));
+ Debug.Assert(pBt.inTransaction == TRANS_WRITE);
+ Debug.Assert(!pBt.readOnly);
#if SQLITE_OMIT_AUTOVACUUM
rc = allocateBtreePage(pBt, ref pRoot, ref pgnoRoot, 1, 0);
@@ -8129,1216 +7400,1079 @@ static int btreeCreateTable( Btree p, ref int piTable, int createTabFlags )
return rc;
}
#else
- if ( pBt.autoVacuum )
- {
- Pgno pgnoMove = 0; /* Move a page here to make room for the root-page */
- MemPage pPageMove = new MemPage(); /* The page to move to. */
-
- /* Creating a new table may probably require moving an existing database
- ** to make room for the new tables root page. In case this page turns
- ** out to be an overflow page, delete all overflow page-map caches
- ** held by open cursors.
- */
- invalidateAllOverflowCache( pBt );
-
- /* Read the value of meta[3] from the database to determine where the
- ** root page of the new table should go. meta[3] is the largest root-page
- ** created so far, so the new root-page is (meta[3]+1).
- */
- sqlite3BtreeGetMeta( p, BTREE_LARGEST_ROOT_PAGE, ref pgnoRoot );
- pgnoRoot++;
-
- /* The new root-page may not be allocated on a pointer-map page, or the
- ** PENDING_BYTE page.
- */
- while ( pgnoRoot == PTRMAP_PAGENO( pBt, pgnoRoot ) ||
- pgnoRoot == PENDING_BYTE_PAGE( pBt ) )
- {
- pgnoRoot++;
- }
- Debug.Assert( pgnoRoot >= 3 );
-
- /* Allocate a page. The page that currently resides at pgnoRoot will
- ** be moved to the allocated page (unless the allocated page happens
- ** to reside at pgnoRoot).
- */
- rc = allocateBtreePage( pBt, ref pPageMove, ref pgnoMove, pgnoRoot, 1 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
+ if (pBt.autoVacuum) {
+ Pgno pgnoMove = 0; /* Move a page here to make room for the root-page */
+ MemPage pPageMove = new MemPage(); /* The page to move to. */
+
+ /* Creating a new table may probably require moving an existing database
+ ** to make room for the new tables root page. In case this page turns
+ ** out to be an overflow page, delete all overflow page-map caches
+ ** held by open cursors.
+ */
+ invalidateAllOverflowCache(pBt);
+
+ /* Read the value of meta[3] from the database to determine where the
+ ** root page of the new table should go. meta[3] is the largest root-page
+ ** created so far, so the new root-page is (meta[3]+1).
+ */
+ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, ref pgnoRoot);
+ pgnoRoot++;
+
+ /* The new root-page may not be allocated on a pointer-map page, or the
+ ** PENDING_BYTE page.
+ */
+ while (pgnoRoot == PTRMAP_PAGENO(pBt, pgnoRoot) ||
+ pgnoRoot == PENDING_BYTE_PAGE(pBt)) {
+ pgnoRoot++;
+ }
+ Debug.Assert(pgnoRoot >= 3);
+
+ /* Allocate a page. The page that currently resides at pgnoRoot will
+ ** be moved to the allocated page (unless the allocated page happens
+ ** to reside at pgnoRoot).
+ */
+ rc = allocateBtreePage(pBt, ref pPageMove, ref pgnoMove, pgnoRoot, 1);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+
+ if (pgnoMove != pgnoRoot) {
+ /* pgnoRoot is the page that will be used for the root-page of
+ ** the new table (assuming an error did not occur). But we were
+ ** allocated pgnoMove. If required (i.e. if it was not allocated
+ ** by extending the file), the current page at position pgnoMove
+ ** is already journaled.
+ */
+ u8 eType = 0;
+ Pgno iPtrPage = 0;
+
+ releasePage(pPageMove);
+
+ /* Move the page currently at pgnoRoot to pgnoMove. */
+ rc = btreeGetPage(pBt, pgnoRoot, ref pRoot, 0);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ rc = ptrmapGet(pBt, pgnoRoot, ref eType, ref iPtrPage);
+ if (eType == PTRMAP_ROOTPAGE || eType == PTRMAP_FREEPAGE) {
+ rc = SQLITE_CORRUPT_BKPT();
+ }
+ if (rc != SQLITE_OK) {
+ releasePage(pRoot);
+ return rc;
+ }
+ Debug.Assert(eType != PTRMAP_ROOTPAGE);
+ Debug.Assert(eType != PTRMAP_FREEPAGE);
+ rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
+ releasePage(pRoot);
+
+ /* Obtain the page at pgnoRoot */
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ rc = btreeGetPage(pBt, pgnoRoot, ref pRoot, 0);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ rc = sqlite3PagerWrite(pRoot.pDbPage);
+ if (rc != SQLITE_OK) {
+ releasePage(pRoot);
+ return rc;
+ }
+ } else {
+ pRoot = pPageMove;
+ }
+
+ /* Update the pointer-map and meta-data with the new root-page number. */
+ ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, ref rc);
+ if (rc != 0) {
+ releasePage(pRoot);
+ return rc;
+ }
+
+ /* When the new root page was allocated, page 1 was made writable in
+ ** order either to increase the database filesize, or to decrement the
+ ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
+ */
+ Debug.Assert(sqlite3PagerIswriteable(pBt.pPage1.pDbPage));
+ rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
+ if (NEVER(rc != 0)) {
+ releasePage(pRoot);
+ return rc;
+ }
+
+ } else {
+ rc = allocateBtreePage(pBt, ref pRoot, ref pgnoRoot, 1, 0);
+ if (rc != 0)
+ return rc;
+ }
+#endif
+ Debug.Assert(sqlite3PagerIswriteable(pRoot.pDbPage));
+ if ((createTabFlags & BTREE_INTKEY) != 0) {
+ ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
+ } else {
+ ptfFlags = PTF_ZERODATA | PTF_LEAF;
+ }
+ zeroPage(pRoot, ptfFlags);
+ sqlite3PagerUnref(pRoot.pDbPage);
+ Debug.Assert((pBt.openFlags & BTREE_SINGLE) == 0 || pgnoRoot == 2);
+ piTable = (int)pgnoRoot;
+ return SQLITE_OK;
+ }
+ static int sqlite3BtreeCreateTable(Btree p, ref int piTable, int flags) {
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = btreeCreateTable(p, ref piTable, flags);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
- if ( pgnoMove != pgnoRoot )
- {
- /* pgnoRoot is the page that will be used for the root-page of
- ** the new table (assuming an error did not occur). But we were
- ** allocated pgnoMove. If required (i.e. if it was not allocated
- ** by extending the file), the current page at position pgnoMove
- ** is already journaled.
- */
- u8 eType = 0;
- Pgno iPtrPage = 0;
-
- releasePage( pPageMove );
-
- /* Move the page currently at pgnoRoot to pgnoMove. */
- rc = btreeGetPage( pBt, pgnoRoot, ref pRoot, 0 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- rc = ptrmapGet( pBt, pgnoRoot, ref eType, ref iPtrPage );
- if ( eType == PTRMAP_ROOTPAGE || eType == PTRMAP_FREEPAGE )
- {
- rc = SQLITE_CORRUPT_BKPT();
- }
- if ( rc != SQLITE_OK )
- {
- releasePage( pRoot );
- return rc;
- }
- Debug.Assert( eType != PTRMAP_ROOTPAGE );
- Debug.Assert( eType != PTRMAP_FREEPAGE );
- rc = relocatePage( pBt, pRoot, eType, iPtrPage, pgnoMove, 0 );
- releasePage( pRoot );
-
- /* Obtain the page at pgnoRoot */
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- rc = btreeGetPage( pBt, pgnoRoot, ref pRoot, 0 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- rc = sqlite3PagerWrite( pRoot.pDbPage );
- if ( rc != SQLITE_OK )
- {
- releasePage( pRoot );
- return rc;
- }
- }
- else
- {
- pRoot = pPageMove;
- }
+ /*
+ ** Erase the given database page and all its children. Return
+ ** the page to the freelist.
+ */
+ static int clearDatabasePage(
+ BtShared pBt, /* The BTree that contains the table */
+ Pgno pgno, /* Page number to clear */
+ int freePageFlag, /* Deallocate page if true */
+ ref int pnChange /* Add number of Cells freed to this counter */
+ ) {
+ MemPage pPage = new MemPage();
+ int rc;
+ byte[] pCell;
+ int i;
+
+ Debug.Assert(sqlite3_mutex_held(pBt.mutex));
+ if (pgno > btreePagecount(pBt)) {
+ return SQLITE_CORRUPT_BKPT();
+ }
- /* Update the pointer-map and meta-data with the new root-page number. */
- ptrmapPut( pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, ref rc );
- if ( rc != 0 )
- {
- releasePage( pRoot );
- return rc;
- }
+ rc = getAndInitPage(pBt, pgno, ref pPage);
+ if (rc != 0)
+ return rc;
+ for (i = 0; i < pPage.nCell; i++) {
+ int iCell = findCell(pPage, i);
+ pCell = pPage.aData; // pCell = findCell( pPage, i );
+ if (0 == pPage.leaf) {
+ rc = clearDatabasePage(pBt, sqlite3Get4byte(pCell, iCell), 1, ref pnChange);
+ if (rc != 0)
+ goto cleardatabasepage_out;
+ }
+ rc = clearCell(pPage, iCell);
+ if (rc != 0)
+ goto cleardatabasepage_out;
+ }
+ if (0 == pPage.leaf) {
+ rc = clearDatabasePage(pBt, sqlite3Get4byte(pPage.aData, 8), 1, ref pnChange);
+ if (rc != 0)
+ goto cleardatabasepage_out;
+ } else //if (pnChange != 0)
+ {
+ //Debug.Assert(pPage.intKey != 0);
+ pnChange += pPage.nCell;
+ }
+ if (freePageFlag != 0) {
+ freePage(pPage, ref rc);
+ } else if ((rc = sqlite3PagerWrite(pPage.pDbPage)) == 0) {
+ zeroPage(pPage, pPage.aData[0] | PTF_LEAF);
+ }
- /* When the new root page was allocated, page 1 was made writable in
- ** order either to increase the database filesize, or to decrement the
- ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
- */
- Debug.Assert( sqlite3PagerIswriteable( pBt.pPage1.pDbPage ) );
- rc = sqlite3BtreeUpdateMeta( p, 4, pgnoRoot );
- if ( NEVER( rc != 0 ) )
- {
- releasePage( pRoot );
- return rc;
- }
+ cleardatabasepage_out:
+ releasePage(pPage);
+ return rc;
+ }
- }
- else
- {
- rc = allocateBtreePage( pBt, ref pRoot, ref pgnoRoot, 1, 0 );
- if ( rc != 0 )
- return rc;
- }
-#endif
- Debug.Assert( sqlite3PagerIswriteable( pRoot.pDbPage ) );
- if ( ( createTabFlags & BTREE_INTKEY ) != 0 )
- {
- ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
- }
- else
- {
- ptfFlags = PTF_ZERODATA | PTF_LEAF;
- }
- zeroPage( pRoot, ptfFlags );
- sqlite3PagerUnref( pRoot.pDbPage );
- Debug.Assert( ( pBt.openFlags & BTREE_SINGLE ) == 0 || pgnoRoot == 2 );
- piTable = (int)pgnoRoot;
- return SQLITE_OK;
-}
-static int sqlite3BtreeCreateTable( Btree p, ref int piTable, int flags )
-{
- int rc;
- sqlite3BtreeEnter( p );
- rc = btreeCreateTable( p, ref piTable, flags );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** Delete all information from a single table in the database. iTable is
+ ** the page number of the root of the table. After this routine returns,
+ ** the root page is empty, but still exists.
+ **
+ ** This routine will fail with SQLITE_LOCKED if there are any open
+ ** read cursors on the table. Open write cursors are moved to the
+ ** root of the table.
+ **
+ ** If pnChange is not NULL, then table iTable must be an intkey table. The
+ ** integer value pointed to by pnChange is incremented by the number of
+ ** entries in the table.
+ */
+ static int sqlite3BtreeClearTable(Btree p, int iTable, ref int pnChange) {
+ int rc;
+ BtShared pBt = p.pBt;
+ sqlite3BtreeEnter(p);
+ Debug.Assert(p.inTrans == TRANS_WRITE);
+
+ /* Invalidate all incrblob cursors open on table iTable (assuming iTable
+ ** is the root of a table b-tree - if it is not, the following call is
+ ** a no-op). */
+ invalidateIncrblobCursors(p, 0, 1);
+
+ rc = saveAllCursors(pBt, (Pgno)iTable, null);
+ if (SQLITE_OK == rc) {
+ rc = clearDatabasePage(pBt, (Pgno)iTable, 0, ref pnChange);
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** Erase the given database page and all its children. Return
-** the page to the freelist.
-*/
-static int clearDatabasePage(
-BtShared pBt, /* The BTree that contains the table */
-Pgno pgno, /* Page number to clear */
-int freePageFlag, /* Deallocate page if true */
-ref int pnChange /* Add number of Cells freed to this counter */
-)
-{
- MemPage pPage = new MemPage();
- int rc;
- byte[] pCell;
- int i;
-
- Debug.Assert( sqlite3_mutex_held( pBt.mutex ) );
- if ( pgno > btreePagecount( pBt ) )
- {
- return SQLITE_CORRUPT_BKPT();
- }
-
- rc = getAndInitPage( pBt, pgno, ref pPage );
- if ( rc != 0 )
- return rc;
- for ( i = 0; i < pPage.nCell; i++ )
- {
- int iCell = findCell( pPage, i );
- pCell = pPage.aData; // pCell = findCell( pPage, i );
- if ( 0 == pPage.leaf )
- {
- rc = clearDatabasePage( pBt, sqlite3Get4byte( pCell, iCell ), 1, ref pnChange );
- if ( rc != 0 )
- goto cleardatabasepage_out;
- }
- rc = clearCell( pPage, iCell );
- if ( rc != 0 )
- goto cleardatabasepage_out;
- }
- if ( 0 == pPage.leaf )
- {
- rc = clearDatabasePage( pBt, sqlite3Get4byte( pPage.aData, 8 ), 1, ref pnChange );
- if ( rc != 0 )
- goto cleardatabasepage_out;
- }
- else //if (pnChange != 0)
- {
- //Debug.Assert(pPage.intKey != 0);
- pnChange += pPage.nCell;
- }
- if ( freePageFlag != 0 )
- {
- freePage( pPage, ref rc );
- }
- else if ( ( rc = sqlite3PagerWrite( pPage.pDbPage ) ) == 0 )
- {
- zeroPage( pPage, pPage.aData[0] | PTF_LEAF );
- }
-
-cleardatabasepage_out:
- releasePage( pPage );
- return rc;
-}
+ /*
+ ** Erase all information in a table and add the root of the table to
+ ** the freelist. Except, the root of the principle table (the one on
+ ** page 1) is never added to the freelist.
+ **
+ ** This routine will fail with SQLITE_LOCKED if there are any open
+ ** cursors on the table.
+ **
+ ** If AUTOVACUUM is enabled and the page at iTable is not the last
+ ** root page in the database file, then the last root page
+ ** in the database file is moved into the slot formerly occupied by
+ ** iTable and that last slot formerly occupied by the last root page
+ ** is added to the freelist instead of iTable. In this say, all
+ ** root pages are kept at the beginning of the database file, which
+ ** is necessary for AUTOVACUUM to work right. piMoved is set to the
+ ** page number that used to be the last root page in the file before
+ ** the move. If no page gets moved, piMoved is set to 0.
+ ** The last root page is recorded in meta[3] and the value of
+ ** meta[3] is updated by this procedure.
+ */
+ static int btreeDropTable(Btree p, Pgno iTable, ref int piMoved) {
+ int rc;
+ MemPage pPage = null;
+ BtShared pBt = p.pBt;
+
+ Debug.Assert(sqlite3BtreeHoldsMutex(p));
+ Debug.Assert(p.inTrans == TRANS_WRITE);
+
+ /* It is illegal to drop a table if any cursors are open on the
+ ** database. This is because in auto-vacuum mode the backend may
+ ** need to move another root-page to fill a gap left by the deleted
+ ** root page. If an open cursor was using this page a problem would
+ ** occur.
+ **
+ ** This error is caught long before control reaches this point.
+ */
+ if (NEVER(pBt.pCursor)) {
+ sqlite3ConnectionBlocked(p.db, pBt.pCursor.pBtree.db);
+ return SQLITE_LOCKED_SHAREDCACHE;
+ }
-/*
-** Delete all information from a single table in the database. iTable is
-** the page number of the root of the table. After this routine returns,
-** the root page is empty, but still exists.
-**
-** This routine will fail with SQLITE_LOCKED if there are any open
-** read cursors on the table. Open write cursors are moved to the
-** root of the table.
-**
-** If pnChange is not NULL, then table iTable must be an intkey table. The
-** integer value pointed to by pnChange is incremented by the number of
-** entries in the table.
-*/
-static int sqlite3BtreeClearTable( Btree p, int iTable, ref int pnChange )
-{
- int rc;
- BtShared pBt = p.pBt;
- sqlite3BtreeEnter( p );
- Debug.Assert( p.inTrans == TRANS_WRITE );
-
- /* Invalidate all incrblob cursors open on table iTable (assuming iTable
- ** is the root of a table b-tree - if it is not, the following call is
- ** a no-op). */
- invalidateIncrblobCursors( p, 0, 1 );
-
- rc = saveAllCursors( pBt, (Pgno)iTable, null );
- if ( SQLITE_OK == rc )
- {
- rc = clearDatabasePage( pBt, (Pgno)iTable, 0, ref pnChange );
- }
- sqlite3BtreeLeave( p );
- return rc;
-}
+ rc = btreeGetPage(pBt, (Pgno)iTable, ref pPage, 0);
+ if (rc != 0)
+ return rc;
+ int Dummy0 = 0;
+ rc = sqlite3BtreeClearTable(p, (int)iTable, ref Dummy0);
+ if (rc != 0) {
+ releasePage(pPage);
+ return rc;
+ }
-/*
-** Erase all information in a table and add the root of the table to
-** the freelist. Except, the root of the principle table (the one on
-** page 1) is never added to the freelist.
-**
-** This routine will fail with SQLITE_LOCKED if there are any open
-** cursors on the table.
-**
-** If AUTOVACUUM is enabled and the page at iTable is not the last
-** root page in the database file, then the last root page
-** in the database file is moved into the slot formerly occupied by
-** iTable and that last slot formerly occupied by the last root page
-** is added to the freelist instead of iTable. In this say, all
-** root pages are kept at the beginning of the database file, which
-** is necessary for AUTOVACUUM to work right. piMoved is set to the
-** page number that used to be the last root page in the file before
-** the move. If no page gets moved, piMoved is set to 0.
-** The last root page is recorded in meta[3] and the value of
-** meta[3] is updated by this procedure.
-*/
-static int btreeDropTable( Btree p, Pgno iTable, ref int piMoved )
-{
- int rc;
- MemPage pPage = null;
- BtShared pBt = p.pBt;
-
- Debug.Assert( sqlite3BtreeHoldsMutex( p ) );
- Debug.Assert( p.inTrans == TRANS_WRITE );
-
- /* It is illegal to drop a table if any cursors are open on the
- ** database. This is because in auto-vacuum mode the backend may
- ** need to move another root-page to fill a gap left by the deleted
- ** root page. If an open cursor was using this page a problem would
- ** occur.
- **
- ** This error is caught long before control reaches this point.
- */
- if ( NEVER( pBt.pCursor ) )
- {
- sqlite3ConnectionBlocked( p.db, pBt.pCursor.pBtree.db );
- return SQLITE_LOCKED_SHAREDCACHE;
- }
-
- rc = btreeGetPage( pBt, (Pgno)iTable, ref pPage, 0 );
- if ( rc != 0 )
- return rc;
- int Dummy0 = 0;
- rc = sqlite3BtreeClearTable( p, (int)iTable, ref Dummy0 );
- if ( rc != 0 )
- {
- releasePage( pPage );
- return rc;
- }
-
- piMoved = 0;
-
- if ( iTable > 1 )
- {
+ piMoved = 0;
+
+ if (iTable > 1) {
#if SQLITE_OMIT_AUTOVACUUM
freePage(pPage, ref rc);
releasePage(pPage);
#else
- if ( pBt.autoVacuum )
- {
- Pgno maxRootPgno = 0;
- sqlite3BtreeGetMeta( p, BTREE_LARGEST_ROOT_PAGE, ref maxRootPgno );
-
- if ( iTable == maxRootPgno )
- {
- /* If the table being dropped is the table with the largest root-page
- ** number in the database, put the root page on the free list.
- */
- freePage( pPage, ref rc );
- releasePage( pPage );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- }
- else
- {
- /* The table being dropped does not have the largest root-page
- ** number in the database. So move the page that does into the
- ** gap left by the deleted root-page.
- */
- MemPage pMove = new MemPage();
- releasePage( pPage );
- rc = btreeGetPage( pBt, maxRootPgno, ref pMove, 0 );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- rc = relocatePage( pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0 );
- releasePage( pMove );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- pMove = null;
- rc = btreeGetPage( pBt, maxRootPgno, ref pMove, 0 );
- freePage( pMove, ref rc );
- releasePage( pMove );
- if ( rc != SQLITE_OK )
- {
- return rc;
- }
- piMoved = (int)maxRootPgno;
- }
-
- /* Set the new 'max-root-page' value in the database header. This
- ** is the old value less one, less one more if that happens to
- ** be a root-page number, less one again if that is the
- ** PENDING_BYTE_PAGE.
- */
- maxRootPgno--;
- while ( maxRootPgno == PENDING_BYTE_PAGE( pBt )
- || PTRMAP_ISPAGE( pBt, maxRootPgno ) )
- {
- maxRootPgno--;
- }
- Debug.Assert( maxRootPgno != PENDING_BYTE_PAGE( pBt ) );
-
- rc = sqlite3BtreeUpdateMeta( p, 4, maxRootPgno );
- }
- else
- {
- freePage( pPage, ref rc );
- releasePage( pPage );
- }
+ if (pBt.autoVacuum) {
+ Pgno maxRootPgno = 0;
+ sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, ref maxRootPgno);
+
+ if (iTable == maxRootPgno) {
+ /* If the table being dropped is the table with the largest root-page
+ ** number in the database, put the root page on the free list.
+ */
+ freePage(pPage, ref rc);
+ releasePage(pPage);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ } else {
+ /* The table being dropped does not have the largest root-page
+ ** number in the database. So move the page that does into the
+ ** gap left by the deleted root-page.
+ */
+ MemPage pMove = new MemPage();
+ releasePage(pPage);
+ rc = btreeGetPage(pBt, maxRootPgno, ref pMove, 0);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
+ releasePage(pMove);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ pMove = null;
+ rc = btreeGetPage(pBt, maxRootPgno, ref pMove, 0);
+ freePage(pMove, ref rc);
+ releasePage(pMove);
+ if (rc != SQLITE_OK) {
+ return rc;
+ }
+ piMoved = (int)maxRootPgno;
+ }
+
+ /* Set the new 'max-root-page' value in the database header. This
+ ** is the old value less one, less one more if that happens to
+ ** be a root-page number, less one again if that is the
+ ** PENDING_BYTE_PAGE.
+ */
+ maxRootPgno--;
+ while (maxRootPgno == PENDING_BYTE_PAGE(pBt)
+ || PTRMAP_ISPAGE(pBt, maxRootPgno)) {
+ maxRootPgno--;
+ }
+ Debug.Assert(maxRootPgno != PENDING_BYTE_PAGE(pBt));
+
+ rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
+ } else {
+ freePage(pPage, ref rc);
+ releasePage(pPage);
+ }
#endif
- }
- else
- {
- /* If sqlite3BtreeDropTable was called on page 1.
- ** This really never should happen except in a corrupt
- ** database.
- */
- zeroPage( pPage, PTF_INTKEY | PTF_LEAF );
- releasePage( pPage );
- }
- return rc;
-}
-static int sqlite3BtreeDropTable( Btree p, int iTable, ref int piMoved )
-{
- int rc;
- sqlite3BtreeEnter( p );
- rc = btreeDropTable( p, (u32)iTable, ref piMoved );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ } else {
+ /* If sqlite3BtreeDropTable was called on page 1.
+ ** This really never should happen except in a corrupt
+ ** database.
+ */
+ zeroPage(pPage, PTF_INTKEY | PTF_LEAF);
+ releasePage(pPage);
+ }
+ return rc;
+ }
+ static int sqlite3BtreeDropTable(Btree p, int iTable, ref int piMoved) {
+ int rc;
+ sqlite3BtreeEnter(p);
+ rc = btreeDropTable(p, (u32)iTable, ref piMoved);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
-/*
-** This function may only be called if the b-tree connection already
-** has a read or write transaction open on the database.
-**
-** Read the meta-information out of a database file. Meta[0]
-** is the number of free pages currently in the database. Meta[1]
-** through meta[15] are available for use by higher layers. Meta[0]
-** is read-only, the others are read/write.
-**
-** The schema layer numbers meta values differently. At the schema
-** layer (and the SetCookie and ReadCookie opcodes) the number of
-** free pages is not visible. So Cookie[0] is the same as Meta[1].
-*/
-static void sqlite3BtreeGetMeta( Btree p, int idx, ref u32 pMeta )
-{
- BtShared pBt = p.pBt;
+ /*
+ ** This function may only be called if the b-tree connection already
+ ** has a read or write transaction open on the database.
+ **
+ ** Read the meta-information out of a database file. Meta[0]
+ ** is the number of free pages currently in the database. Meta[1]
+ ** through meta[15] are available for use by higher layers. Meta[0]
+ ** is read-only, the others are read/write.
+ **
+ ** The schema layer numbers meta values differently. At the schema
+ ** layer (and the SetCookie and ReadCookie opcodes) the number of
+ ** free pages is not visible. So Cookie[0] is the same as Meta[1].
+ */
+ static void sqlite3BtreeGetMeta(Btree p, int idx, ref u32 pMeta) {
+ BtShared pBt = p.pBt;
- sqlite3BtreeEnter( p );
- Debug.Assert( p.inTrans > TRANS_NONE );
- Debug.Assert( SQLITE_OK == querySharedCacheTableLock( p, MASTER_ROOT, READ_LOCK ) );
- Debug.Assert( pBt.pPage1 != null );
- Debug.Assert( idx >= 0 && idx <= 15 );
+ sqlite3BtreeEnter(p);
+ Debug.Assert(p.inTrans > TRANS_NONE);
+ Debug.Assert(SQLITE_OK == querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK));
+ Debug.Assert(pBt.pPage1 != null);
+ Debug.Assert(idx >= 0 && idx <= 15);
- pMeta = sqlite3Get4byte( pBt.pPage1.aData, 36 + idx * 4 );
+ pMeta = sqlite3Get4byte(pBt.pPage1.aData, 36 + idx * 4);
- /* If auto-vacuum is disabled in this build and this is an auto-vacuum
- ** database, mark the database as read-only. */
+ /* If auto-vacuum is disabled in this build and this is an auto-vacuum
+ ** database, mark the database as read-only. */
#if SQLITE_OMIT_AUTOVACUUM
if( idx==BTREE_LARGEST_ROOT_PAGE && pMeta>0 ) pBt.readOnly = 1;
#endif
- sqlite3BtreeLeave( p );
-}
+ sqlite3BtreeLeave(p);
+ }
-/*
-** Write meta-information back into the database. Meta[0] is
-** read-only and may not be written.
-*/
-static int sqlite3BtreeUpdateMeta( Btree p, int idx, u32 iMeta )
-{
- BtShared pBt = p.pBt;
- byte[] pP1;
- int rc;
- Debug.Assert( idx >= 1 && idx <= 15 );
- sqlite3BtreeEnter( p );
- Debug.Assert( p.inTrans == TRANS_WRITE );
- Debug.Assert( pBt.pPage1 != null );
- pP1 = pBt.pPage1.aData;
- rc = sqlite3PagerWrite( pBt.pPage1.pDbPage );
- if ( rc == SQLITE_OK )
- {
- sqlite3Put4byte( pP1, 36 + idx * 4, iMeta );
+ /*
+ ** Write meta-information back into the database. Meta[0] is
+ ** read-only and may not be written.
+ */
+ static int sqlite3BtreeUpdateMeta(Btree p, int idx, u32 iMeta) {
+ BtShared pBt = p.pBt;
+ byte[] pP1;
+ int rc;
+ Debug.Assert(idx >= 1 && idx <= 15);
+ sqlite3BtreeEnter(p);
+ Debug.Assert(p.inTrans == TRANS_WRITE);
+ Debug.Assert(pBt.pPage1 != null);
+ pP1 = pBt.pPage1.aData;
+ rc = sqlite3PagerWrite(pBt.pPage1.pDbPage);
+ if (rc == SQLITE_OK) {
+ sqlite3Put4byte(pP1, 36 + idx * 4, iMeta);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( idx == BTREE_INCR_VACUUM )
- {
- Debug.Assert( pBt.autoVacuum || iMeta == 0 );
- Debug.Assert( iMeta == 0 || iMeta == 1 );
- pBt.incrVacuum = iMeta != 0;
- }
+ if (idx == BTREE_INCR_VACUUM) {
+ Debug.Assert(pBt.autoVacuum || iMeta == 0);
+ Debug.Assert(iMeta == 0 || iMeta == 1);
+ pBt.incrVacuum = iMeta != 0;
+ }
#endif
- }
- sqlite3BtreeLeave( p );
- return rc;
-}
+ }
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
#if !SQLITE_OMIT_BTREECOUNT
-/*
-** The first argument, pCur, is a cursor opened on some b-tree. Count the
-** number of entries in the b-tree and write the result to pnEntry.
-**
-** SQLITE_OK is returned if the operation is successfully executed.
-** Otherwise, if an error is encountered (i.e. an IO error or database
-** corruption) an SQLite error code is returned.
-*/
-static int sqlite3BtreeCount( BtCursor pCur, ref i64 pnEntry )
-{
- i64 nEntry = 0; /* Value to return in pnEntry */
- int rc; /* Return code */
- rc = moveToRoot( pCur );
-
- /* Unless an error occurs, the following loop runs one iteration for each
- ** page in the B-Tree structure (not including overflow pages).
- */
- while ( rc == SQLITE_OK )
- {
- int iIdx; /* Index of child node in parent */
- MemPage pPage; /* Current page of the b-tree */
-
- /* If this is a leaf page or the tree is not an int-key tree, then
- ** this page contains countable entries. Increment the entry counter
- ** accordingly.
- */
- pPage = pCur.apPage[pCur.iPage];
- if ( pPage.leaf != 0 || 0 == pPage.intKey )
- {
- nEntry += pPage.nCell;
- }
-
- /* pPage is a leaf node. This loop navigates the cursor so that it
- ** points to the first interior cell that it points to the parent of
- ** the next page in the tree that has not yet been visited. The
- ** pCur.aiIdx[pCur.iPage] value is set to the index of the parent cell
- ** of the page, or to the number of cells in the page if the next page
- ** to visit is the right-child of its parent.
- **
- ** If all pages in the tree have been visited, return SQLITE_OK to the
- ** caller.
- */
- if ( pPage.leaf != 0 )
- {
- do
- {
- if ( pCur.iPage == 0 )
- {
- /* All pages of the b-tree have been visited. Return successfully. */
- pnEntry = nEntry;
- return SQLITE_OK;
- }
- moveToParent( pCur );
- } while ( pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell );
-
- pCur.aiIdx[pCur.iPage]++;
- pPage = pCur.apPage[pCur.iPage];
- }
-
- /* Descend to the child node of the cell that the cursor currently
- ** points at. This is the right-child if (iIdx==pPage.nCell).
- */
- iIdx = pCur.aiIdx[pCur.iPage];
- if ( iIdx == pPage.nCell )
- {
- rc = moveToChild( pCur, sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 ) );
- }
- else
- {
- rc = moveToChild( pCur, sqlite3Get4byte( pPage.aData, findCell( pPage, iIdx ) ) );
- }
- }
+ /*
+ ** The first argument, pCur, is a cursor opened on some b-tree. Count the
+ ** number of entries in the b-tree and write the result to pnEntry.
+ **
+ ** SQLITE_OK is returned if the operation is successfully executed.
+ ** Otherwise, if an error is encountered (i.e. an IO error or database
+ ** corruption) an SQLite error code is returned.
+ */
+ static int sqlite3BtreeCount(BtCursor pCur, ref i64 pnEntry) {
+ i64 nEntry = 0; /* Value to return in pnEntry */
+ int rc; /* Return code */
+ rc = moveToRoot(pCur);
+
+ /* Unless an error occurs, the following loop runs one iteration for each
+ ** page in the B-Tree structure (not including overflow pages).
+ */
+ while (rc == SQLITE_OK) {
+ int iIdx; /* Index of child node in parent */
+ MemPage pPage; /* Current page of the b-tree */
+
+ /* If this is a leaf page or the tree is not an int-key tree, then
+ ** this page contains countable entries. Increment the entry counter
+ ** accordingly.
+ */
+ pPage = pCur.apPage[pCur.iPage];
+ if (pPage.leaf != 0 || 0 == pPage.intKey) {
+ nEntry += pPage.nCell;
+ }
+
+ /* pPage is a leaf node. This loop navigates the cursor so that it
+ ** points to the first interior cell that it points to the parent of
+ ** the next page in the tree that has not yet been visited. The
+ ** pCur.aiIdx[pCur.iPage] value is set to the index of the parent cell
+ ** of the page, or to the number of cells in the page if the next page
+ ** to visit is the right-child of its parent.
+ **
+ ** If all pages in the tree have been visited, return SQLITE_OK to the
+ ** caller.
+ */
+ if (pPage.leaf != 0) {
+ do {
+ if (pCur.iPage == 0) {
+ /* All pages of the b-tree have been visited. Return successfully. */
+ pnEntry = nEntry;
+ return SQLITE_OK;
+ }
+ moveToParent(pCur);
+ } while (pCur.aiIdx[pCur.iPage] >= pCur.apPage[pCur.iPage].nCell);
+
+ pCur.aiIdx[pCur.iPage]++;
+ pPage = pCur.apPage[pCur.iPage];
+ }
+
+ /* Descend to the child node of the cell that the cursor currently
+ ** points at. This is the right-child if (iIdx==pPage.nCell).
+ */
+ iIdx = pCur.aiIdx[pCur.iPage];
+ if (iIdx == pPage.nCell) {
+ rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8));
+ } else {
+ rc = moveToChild(pCur, sqlite3Get4byte(pPage.aData, findCell(pPage, iIdx)));
+ }
+ }
- /* An error has occurred. Return an error code. */
- return rc;
-}
+ /* An error has occurred. Return an error code. */
+ return rc;
+ }
#endif
-/*
-** Return the pager associated with a BTree. This routine is used for
-** testing and debugging only.
-*/
-static Pager sqlite3BtreePager( Btree p )
-{
- return p.pBt.pPager;
-}
+ /*
+ ** Return the pager associated with a BTree. This routine is used for
+ ** testing and debugging only.
+ */
+ static Pager sqlite3BtreePager(Btree p) {
+ return p.pBt.pPager;
+ }
#if !SQLITE_OMIT_INTEGRITY_CHECK
-/*
-** Append a message to the error message string.
-*/
-static void checkAppendMsg(
-IntegrityCk pCheck,
-string zMsg1,
-string zFormat,
-params object[] ap
-)
-{
- if ( 0 == pCheck.mxErr )
- return;
- //va_list ap;
- lock ( lock_va_list )
- {
- pCheck.mxErr--;
- pCheck.nErr++;
- va_start( ap, zFormat );
- if ( pCheck.errMsg.zText.Length != 0 )
- {
- sqlite3StrAccumAppend( pCheck.errMsg, "\n", 1 );
- }
- if ( zMsg1.Length > 0 )
- {
- sqlite3StrAccumAppend( pCheck.errMsg, zMsg1.ToString(), -1 );
- }
- sqlite3VXPrintf( pCheck.errMsg, 1, zFormat, ap );
- va_end( ref ap );
- }
-}
+ /*
+ ** Append a message to the error message string.
+ */
+ static void checkAppendMsg(
+ IntegrityCk pCheck,
+ string zMsg1,
+ string zFormat,
+ params object[] ap
+ ) {
+ if (0 == pCheck.mxErr)
+ return;
+ //va_list ap;
+ lock (lock_va_list) {
+ pCheck.mxErr--;
+ pCheck.nErr++;
+ va_start(ap, zFormat);
+ if (pCheck.errMsg.zText.Length != 0) {
+ sqlite3StrAccumAppend(pCheck.errMsg, "\n", 1);
+ }
+ if (zMsg1.Length > 0) {
+ sqlite3StrAccumAppend(pCheck.errMsg, zMsg1.ToString(), -1);
+ }
+ sqlite3VXPrintf(pCheck.errMsg, 1, zFormat, ap);
+ va_end(ref ap);
+ }
+ }
-static void checkAppendMsg(
-IntegrityCk pCheck,
-StringBuilder zMsg1,
-string zFormat,
-params object[] ap
-)
-{
- if ( 0 == pCheck.mxErr )
- return;
- //va_list ap;
- lock ( lock_va_list )
- {
- pCheck.mxErr--;
- pCheck.nErr++;
- va_start( ap, zFormat );
- if ( pCheck.errMsg.zText.Length != 0 )
- {
- sqlite3StrAccumAppend( pCheck.errMsg, "\n", 1 );
- }
- if ( zMsg1.Length > 0 )
- {
- sqlite3StrAccumAppend( pCheck.errMsg, zMsg1.ToString(), -1 );
- }
- sqlite3VXPrintf( pCheck.errMsg, 1, zFormat, ap );
- va_end( ref ap );
- }
- //if( pCheck.errMsg.mallocFailed ){
- // pCheck.mallocFailed = 1;
- //}
-}
+ static void checkAppendMsg(
+ IntegrityCk pCheck,
+ StringBuilder zMsg1,
+ string zFormat,
+ params object[] ap
+ ) {
+ if (0 == pCheck.mxErr)
+ return;
+ //va_list ap;
+ lock (lock_va_list) {
+ pCheck.mxErr--;
+ pCheck.nErr++;
+ va_start(ap, zFormat);
+ if (pCheck.errMsg.zText.Length != 0) {
+ sqlite3StrAccumAppend(pCheck.errMsg, "\n", 1);
+ }
+ if (zMsg1.Length > 0) {
+ sqlite3StrAccumAppend(pCheck.errMsg, zMsg1.ToString(), -1);
+ }
+ sqlite3VXPrintf(pCheck.errMsg, 1, zFormat, ap);
+ va_end(ref ap);
+ }
+ //if( pCheck.errMsg.mallocFailed ){
+ // pCheck.mallocFailed = 1;
+ //}
+ }
#endif //* SQLITE_OMIT_INTEGRITY_CHECK */
#if !SQLITE_OMIT_INTEGRITY_CHECK
-/*
-** Add 1 to the reference count for page iPage. If this is the second
-** reference to the page, add an error message to pCheck.zErrMsg.
-** Return 1 if there are 2 ore more references to the page and 0 if
-** if this is the first reference to the page.
-**
-** Also check that the page number is in bounds.
-*/
-static int checkRef( IntegrityCk pCheck, Pgno iPage, string zContext )
-{
- if ( iPage == 0 )
- return 1;
- if ( iPage > pCheck.nPage )
- {
- checkAppendMsg( pCheck, zContext, "invalid page number %d", iPage );
- return 1;
- }
- if ( pCheck.anRef[iPage] == 1 )
- {
- checkAppendMsg( pCheck, zContext, "2nd reference to page %d", iPage );
- return 1;
- }
- return ( ( pCheck.anRef[iPage]++ ) > 1 ) ? 1 : 0;
-}
+ /*
+ ** Add 1 to the reference count for page iPage. If this is the second
+ ** reference to the page, add an error message to pCheck.zErrMsg.
+ ** Return 1 if there are 2 ore more references to the page and 0 if
+ ** if this is the first reference to the page.
+ **
+ ** Also check that the page number is in bounds.
+ */
+ static int checkRef(IntegrityCk pCheck, Pgno iPage, string zContext) {
+ if (iPage == 0)
+ return 1;
+ if (iPage > pCheck.nPage) {
+ checkAppendMsg(pCheck, zContext, "invalid page number %d", iPage);
+ return 1;
+ }
+ if (pCheck.anRef[iPage] == 1) {
+ checkAppendMsg(pCheck, zContext, "2nd reference to page %d", iPage);
+ return 1;
+ }
+ return ((pCheck.anRef[iPage]++) > 1) ? 1 : 0;
+ }
#if !SQLITE_OMIT_AUTOVACUUM
-/*
-** Check that the entry in the pointer-map for page iChild maps to
-** page iParent, pointer type ptrType. If not, append an error message
-** to pCheck.
-*/
-static void checkPtrmap(
-IntegrityCk pCheck, /* Integrity check context */
-Pgno iChild, /* Child page number */
-u8 eType, /* Expected pointer map type */
-Pgno iParent, /* Expected pointer map parent page number */
-string zContext /* Context description (used for error msg) */
-)
-{
- int rc;
- u8 ePtrmapType = 0;
- Pgno iPtrmapParent = 0;
-
- rc = ptrmapGet( pCheck.pBt, iChild, ref ePtrmapType, ref iPtrmapParent );
- if ( rc != SQLITE_OK )
- {
- //if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck.mallocFailed = 1;
- checkAppendMsg( pCheck, zContext, "Failed to read ptrmap key=%d", iChild );
- return;
- }
-
- if ( ePtrmapType != eType || iPtrmapParent != iParent )
- {
- checkAppendMsg( pCheck, zContext,
- "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
- iChild, eType, iParent, ePtrmapType, iPtrmapParent );
- }
-}
+ /*
+ ** Check that the entry in the pointer-map for page iChild maps to
+ ** page iParent, pointer type ptrType. If not, append an error message
+ ** to pCheck.
+ */
+ static void checkPtrmap(
+ IntegrityCk pCheck, /* Integrity check context */
+ Pgno iChild, /* Child page number */
+ u8 eType, /* Expected pointer map type */
+ Pgno iParent, /* Expected pointer map parent page number */
+ string zContext /* Context description (used for error msg) */
+ ) {
+ int rc;
+ u8 ePtrmapType = 0;
+ Pgno iPtrmapParent = 0;
+
+ rc = ptrmapGet(pCheck.pBt, iChild, ref ePtrmapType, ref iPtrmapParent);
+ if (rc != SQLITE_OK) {
+ //if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck.mallocFailed = 1;
+ checkAppendMsg(pCheck, zContext, "Failed to read ptrmap key=%d", iChild);
+ return;
+ }
+
+ if (ePtrmapType != eType || iPtrmapParent != iParent) {
+ checkAppendMsg(pCheck, zContext,
+ "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
+ iChild, eType, iParent, ePtrmapType, iPtrmapParent);
+ }
+ }
#endif
-/*
-** Check the integrity of the freelist or of an overflow page list.
-** Verify that the number of pages on the list is N.
-*/
-static void checkList(
-IntegrityCk pCheck, /* Integrity checking context */
-int isFreeList, /* True for a freelist. False for overflow page list */
-int iPage, /* Page number for first page in the list */
-int N, /* Expected number of pages in the list */
-string zContext /* Context for error messages */
-)
-{
- int i;
- int expected = N;
- int iFirst = iPage;
- while ( N-- > 0 && pCheck.mxErr != 0 )
- {
- PgHdr pOvflPage = new PgHdr();
- byte[] pOvflData;
- if ( iPage < 1 )
- {
- checkAppendMsg( pCheck, zContext,
- "%d of %d pages missing from overflow list starting at %d",
- N + 1, expected, iFirst );
- break;
- }
- if ( checkRef( pCheck, (u32)iPage, zContext ) != 0 )
- break;
- if ( sqlite3PagerGet( pCheck.pPager, (Pgno)iPage, ref pOvflPage ) != 0 )
- {
- checkAppendMsg( pCheck, zContext, "failed to get page %d", iPage );
- break;
- }
- pOvflData = sqlite3PagerGetData( pOvflPage );
- if ( isFreeList != 0 )
- {
- int n = (int)sqlite3Get4byte( pOvflData, 4 );
+ /*
+ ** Check the integrity of the freelist or of an overflow page list.
+ ** Verify that the number of pages on the list is N.
+ */
+ static void checkList(
+ IntegrityCk pCheck, /* Integrity checking context */
+ int isFreeList, /* True for a freelist. False for overflow page list */
+ int iPage, /* Page number for first page in the list */
+ int N, /* Expected number of pages in the list */
+ string zContext /* Context for error messages */
+ ) {
+ int i;
+ int expected = N;
+ int iFirst = iPage;
+ while (N-- > 0 && pCheck.mxErr != 0) {
+ PgHdr pOvflPage = new PgHdr();
+ byte[] pOvflData;
+ if (iPage < 1) {
+ checkAppendMsg(pCheck, zContext,
+ "%d of %d pages missing from overflow list starting at %d",
+ N + 1, expected, iFirst);
+ break;
+ }
+ if (checkRef(pCheck, (u32)iPage, zContext) != 0)
+ break;
+ if (sqlite3PagerGet(pCheck.pPager, (Pgno)iPage, ref pOvflPage) != 0) {
+ checkAppendMsg(pCheck, zContext, "failed to get page %d", iPage);
+ break;
+ }
+ pOvflData = sqlite3PagerGetData(pOvflPage);
+ if (isFreeList != 0) {
+ int n = (int)sqlite3Get4byte(pOvflData, 4);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pCheck.pBt.autoVacuum )
- {
- checkPtrmap( pCheck, (u32)iPage, PTRMAP_FREEPAGE, 0, zContext );
- }
+ if (pCheck.pBt.autoVacuum) {
+ checkPtrmap(pCheck, (u32)iPage, PTRMAP_FREEPAGE, 0, zContext);
+ }
#endif
- if ( n > (int)pCheck.pBt.usableSize / 4 - 2 )
- {
- checkAppendMsg( pCheck, zContext,
- "freelist leaf count too big on page %d", iPage );
- N--;
- }
- else
- {
- for ( i = 0; i < n; i++ )
- {
- Pgno iFreePage = sqlite3Get4byte( pOvflData, 8 + i * 4 );
+ if (n > (int)pCheck.pBt.usableSize / 4 - 2) {
+ checkAppendMsg(pCheck, zContext,
+ "freelist leaf count too big on page %d", iPage);
+ N--;
+ } else {
+ for (i = 0; i < n; i++) {
+ Pgno iFreePage = sqlite3Get4byte(pOvflData, 8 + i * 4);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pCheck.pBt.autoVacuum )
- {
- checkPtrmap( pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext );
- }
+ if (pCheck.pBt.autoVacuum) {
+ checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0, zContext);
+ }
#endif
- checkRef( pCheck, iFreePage, zContext );
- }
- N -= n;
- }
- }
+ checkRef(pCheck, iFreePage, zContext);
+ }
+ N -= n;
+ }
+ }
#if !SQLITE_OMIT_AUTOVACUUM
- else
- {
- /* If this database supports auto-vacuum and iPage is not the last
- ** page in this overflow list, check that the pointer-map entry for
- ** the following page matches iPage.
- */
- if ( pCheck.pBt.autoVacuum && N > 0 )
- {
- i = (int)sqlite3Get4byte( pOvflData );
- checkPtrmap( pCheck, (u32)i, PTRMAP_OVERFLOW2, (u32)iPage, zContext );
- }
- }
+ else {
+ /* If this database supports auto-vacuum and iPage is not the last
+ ** page in this overflow list, check that the pointer-map entry for
+ ** the following page matches iPage.
+ */
+ if (pCheck.pBt.autoVacuum && N > 0) {
+ i = (int)sqlite3Get4byte(pOvflData);
+ checkPtrmap(pCheck, (u32)i, PTRMAP_OVERFLOW2, (u32)iPage, zContext);
+ }
+ }
#endif
- iPage = (int)sqlite3Get4byte( pOvflData );
- sqlite3PagerUnref( pOvflPage );
- }
-}
+ iPage = (int)sqlite3Get4byte(pOvflData);
+ sqlite3PagerUnref(pOvflPage);
+ }
+ }
#endif //* SQLITE_OMIT_INTEGRITY_CHECK */
#if !SQLITE_OMIT_INTEGRITY_CHECK
-/*
-** Do various sanity checks on a single page of a tree. Return
-** the tree depth. Root pages return 0. Parents of root pages
-** return 1, and so forth.
-**
-** These checks are done:
-**
-** 1. Make sure that cells and freeblocks do not overlap
-** but combine to completely cover the page.
-** NO 2. Make sure cell keys are in order.
-** NO 3. Make sure no key is less than or equal to zLowerBound.
-** NO 4. Make sure no key is greater than or equal to zUpperBound.
-** 5. Check the integrity of overflow pages.
-** 6. Recursively call checkTreePage on all children.
-** 7. Verify that the depth of all children is the same.
-** 8. Make sure this page is at least 33% full or else it is
-** the root of the tree.
-*/
+ /*
+ ** Do various sanity checks on a single page of a tree. Return
+ ** the tree depth. Root pages return 0. Parents of root pages
+ ** return 1, and so forth.
+ **
+ ** These checks are done:
+ **
+ ** 1. Make sure that cells and freeblocks do not overlap
+ ** but combine to completely cover the page.
+ ** NO 2. Make sure cell keys are in order.
+ ** NO 3. Make sure no key is less than or equal to zLowerBound.
+ ** NO 4. Make sure no key is greater than or equal to zUpperBound.
+ ** 5. Check the integrity of overflow pages.
+ ** 6. Recursively call checkTreePage on all children.
+ ** 7. Verify that the depth of all children is the same.
+ ** 8. Make sure this page is at least 33% full or else it is
+ ** the root of the tree.
+ */
-static i64 refNULL = 0; //Dummy for C# ref NULL
-
-static int checkTreePage(
-IntegrityCk pCheck, /* Context for the sanity check */
-int iPage, /* Page number of the page to check */
-string zParentContext, /* Parent context */
-ref i64 pnParentMinKey,
-ref i64 pnParentMaxKey,
-object _pnParentMinKey, /* C# Needed to determine if content passed*/
-object _pnParentMaxKey /* C# Needed to determine if content passed*/
-)
-{
- MemPage pPage = new MemPage();
- int i, rc, depth, d2, pgno, cnt;
- int hdr, cellStart;
- int nCell;
- u8[] data;
- BtShared pBt;
- int usableSize;
- StringBuilder zContext = new StringBuilder( 100 );
- byte[] hit = null;
- i64 nMinKey = 0;
- i64 nMaxKey = 0;
-
-
- sqlite3_snprintf( 200, zContext, "Page %d: ", iPage );
-
- /* Check that the page exists
- */
- pBt = pCheck.pBt;
- usableSize = (int)pBt.usableSize;
- if ( iPage == 0 )
- return 0;
- if ( checkRef( pCheck, (u32)iPage, zParentContext ) != 0 )
- return 0;
- if ( ( rc = btreeGetPage( pBt, (Pgno)iPage, ref pPage, 0 ) ) != 0 )
- {
- checkAppendMsg( pCheck, zContext.ToString(),
- "unable to get the page. error code=%d", rc );
- return 0;
- }
-
- /* Clear MemPage.isInit to make sure the corruption detection code in
- ** btreeInitPage() is executed. */
- pPage.isInit = 0;
- if ( ( rc = btreeInitPage( pPage ) ) != 0 )
- {
- Debug.Assert( rc == SQLITE_CORRUPT ); /* The only possible error from InitPage */
- checkAppendMsg( pCheck, zContext.ToString(),
- "btreeInitPage() returns error code %d", rc );
- releasePage( pPage );
- return 0;
- }
-
- /* Check out all the cells.
- */
- depth = 0;
- for ( i = 0; i < pPage.nCell && pCheck.mxErr != 0; i++ )
- {
- u8[] pCell;
- u32 sz;
- CellInfo info = new CellInfo();
-
- /* Check payload overflow pages
- */
- sqlite3_snprintf( 200, zContext,
- "On tree page %d cell %d: ", iPage, i );
- int iCell = findCell( pPage, i ); //pCell = findCell( pPage, i );
- pCell = pPage.aData;
- btreeParseCellPtr( pPage, iCell, ref info ); //btreeParseCellPtr( pPage, pCell, info );
- sz = info.nData;
- if ( 0 == pPage.intKey )
- sz += (u32)info.nKey;
- /* For intKey pages, check that the keys are in order.
- */
- else if ( i == 0 )
- nMinKey = nMaxKey = info.nKey;
- else
- {
- if ( info.nKey <= nMaxKey )
- {
- checkAppendMsg( pCheck, zContext.ToString(),
- "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey );
- }
- nMaxKey = info.nKey;
- }
- Debug.Assert( sz == info.nPayload );
- if ( ( sz > info.nLocal )
- //&& (pCell[info.iOverflow]<=&pPage.aData[pBt.usableSize])
- )
- {
- int nPage = (int)( sz - info.nLocal + usableSize - 5 ) / ( usableSize - 4 );
- Pgno pgnoOvfl = sqlite3Get4byte( pCell, iCell, info.iOverflow );
+ static i64 refNULL = 0; //Dummy for C# ref NULL
+
+ static int checkTreePage(
+ IntegrityCk pCheck, /* Context for the sanity check */
+ int iPage, /* Page number of the page to check */
+ string zParentContext, /* Parent context */
+ ref i64 pnParentMinKey,
+ ref i64 pnParentMaxKey,
+ object _pnParentMinKey, /* C# Needed to determine if content passed*/
+ object _pnParentMaxKey /* C# Needed to determine if content passed*/
+ ) {
+ MemPage pPage = new MemPage();
+ int i, rc, depth, d2, pgno, cnt;
+ int hdr, cellStart;
+ int nCell;
+ u8[] data;
+ BtShared pBt;
+ int usableSize;
+ StringBuilder zContext = new StringBuilder(100);
+ byte[] hit = null;
+ i64 nMinKey = 0;
+ i64 nMaxKey = 0;
+
+
+ sqlite3_snprintf(200, zContext, "Page %d: ", iPage);
+
+ /* Check that the page exists
+ */
+ pBt = pCheck.pBt;
+ usableSize = (int)pBt.usableSize;
+ if (iPage == 0)
+ return 0;
+ if (checkRef(pCheck, (u32)iPage, zParentContext) != 0)
+ return 0;
+ if ((rc = btreeGetPage(pBt, (Pgno)iPage, ref pPage, 0)) != 0) {
+ checkAppendMsg(pCheck, zContext.ToString(),
+ "unable to get the page. error code=%d", rc);
+ return 0;
+ }
+
+ /* Clear MemPage.isInit to make sure the corruption detection code in
+ ** btreeInitPage() is executed. */
+ pPage.isInit = 0;
+ if ((rc = btreeInitPage(pPage)) != 0) {
+ Debug.Assert(rc == SQLITE_CORRUPT); /* The only possible error from InitPage */
+ checkAppendMsg(pCheck, zContext.ToString(),
+ "btreeInitPage() returns error code %d", rc);
+ releasePage(pPage);
+ return 0;
+ }
+
+ /* Check out all the cells.
+ */
+ depth = 0;
+ for (i = 0; i < pPage.nCell && pCheck.mxErr != 0; i++) {
+ u8[] pCell;
+ u32 sz;
+ CellInfo info = new CellInfo();
+
+ /* Check payload overflow pages
+ */
+ sqlite3_snprintf(200, zContext,
+ "On tree page %d cell %d: ", iPage, i);
+ int iCell = findCell(pPage, i); //pCell = findCell( pPage, i );
+ pCell = pPage.aData;
+ btreeParseCellPtr(pPage, iCell, ref info); //btreeParseCellPtr( pPage, pCell, info );
+ sz = info.nData;
+ if (0 == pPage.intKey)
+ sz += (u32)info.nKey;
+ /* For intKey pages, check that the keys are in order.
+ */
+ else if (i == 0)
+ nMinKey = nMaxKey = info.nKey;
+ else {
+ if (info.nKey <= nMaxKey) {
+ checkAppendMsg(pCheck, zContext.ToString(),
+ "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
+ }
+ nMaxKey = info.nKey;
+ }
+ Debug.Assert(sz == info.nPayload);
+ if ((sz > info.nLocal)
+ //&& (pCell[info.iOverflow]<=&pPage.aData[pBt.usableSize])
+ ) {
+ int nPage = (int)(sz - info.nLocal + usableSize - 5) / (usableSize - 4);
+ Pgno pgnoOvfl = sqlite3Get4byte(pCell, iCell, info.iOverflow);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pBt.autoVacuum )
- {
- checkPtrmap( pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, (u32)iPage, zContext.ToString() );
- }
+ if (pBt.autoVacuum) {
+ checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, (u32)iPage, zContext.ToString());
+ }
#endif
- checkList( pCheck, 0, (int)pgnoOvfl, nPage, zContext.ToString() );
- }
+ checkList(pCheck, 0, (int)pgnoOvfl, nPage, zContext.ToString());
+ }
- /* Check sanity of left child page.
- */
- if ( 0 == pPage.leaf )
- {
- pgno = (int)sqlite3Get4byte( pCell, iCell ); //sqlite3Get4byte( pCell );
+ /* Check sanity of left child page.
+ */
+ if (0 == pPage.leaf) {
+ pgno = (int)sqlite3Get4byte(pCell, iCell); //sqlite3Get4byte( pCell );
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pBt.autoVacuum )
- {
- checkPtrmap( pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext.ToString() );
- }
+ if (pBt.autoVacuum) {
+ checkPtrmap(pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext.ToString());
+ }
#endif
- if ( i == 0 )
- d2 = checkTreePage( pCheck, pgno, zContext.ToString(), ref nMinKey, ref refNULL, pCheck, null );
- else
- d2 = checkTreePage( pCheck, pgno, zContext.ToString(), ref nMinKey, ref nMaxKey, pCheck, pCheck );
-
- if ( i > 0 && d2 != depth )
- {
- checkAppendMsg( pCheck, zContext, "Child page depth differs" );
- }
- depth = d2;
- }
- }
- if ( 0 == pPage.leaf )
- {
- pgno = (int)sqlite3Get4byte( pPage.aData, pPage.hdrOffset + 8 );
- sqlite3_snprintf( 200, zContext,
- "On page %d at right child: ", iPage );
+ if (i == 0)
+ d2 = checkTreePage(pCheck, pgno, zContext.ToString(), ref nMinKey, ref refNULL, pCheck, null);
+ else
+ d2 = checkTreePage(pCheck, pgno, zContext.ToString(), ref nMinKey, ref nMaxKey, pCheck, pCheck);
+
+ if (i > 0 && d2 != depth) {
+ checkAppendMsg(pCheck, zContext, "Child page depth differs");
+ }
+ depth = d2;
+ }
+ }
+ if (0 == pPage.leaf) {
+ pgno = (int)sqlite3Get4byte(pPage.aData, pPage.hdrOffset + 8);
+ sqlite3_snprintf(200, zContext,
+ "On page %d at right child: ", iPage);
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pBt.autoVacuum )
- {
- checkPtrmap( pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext.ToString() );
- }
+ if (pBt.autoVacuum) {
+ checkPtrmap(pCheck, (u32)pgno, PTRMAP_BTREE, (u32)iPage, zContext.ToString());
+ }
#endif
- // checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
- if ( 0 == pPage.nCell )
- checkTreePage( pCheck, pgno, zContext.ToString(), ref refNULL, ref refNULL, null, null );
- else
- checkTreePage( pCheck, pgno, zContext.ToString(), ref refNULL, ref nMaxKey, null, pCheck );
- }
-
- /* For intKey leaf pages, check that the min/max keys are in order
- ** with any left/parent/right pages.
- */
- if ( pPage.leaf != 0 && pPage.intKey != 0 )
- {
- /* if we are a left child page */
- if ( _pnParentMinKey != null )
- {
- /* if we are the left most child page */
- if ( _pnParentMaxKey == null )
- {
- if ( nMaxKey > pnParentMinKey )
- {
- checkAppendMsg( pCheck, zContext,
- "Rowid %lld out of order (max larger than parent min of %lld)",
- nMaxKey, pnParentMinKey );
- }
- }
- else
- {
- if ( nMinKey <= pnParentMinKey )
- {
- checkAppendMsg( pCheck, zContext,
- "Rowid %lld out of order (min less than parent min of %lld)",
- nMinKey, pnParentMinKey );
- }
- if ( nMaxKey > pnParentMaxKey )
- {
- checkAppendMsg( pCheck, zContext,
- "Rowid %lld out of order (max larger than parent max of %lld)",
- nMaxKey, pnParentMaxKey );
- }
- pnParentMinKey = nMaxKey;
- }
- /* else if we're a right child page */
- }
- else if ( _pnParentMaxKey != null )
- {
- if ( nMinKey <= pnParentMaxKey )
- {
- checkAppendMsg( pCheck, zContext,
- "Rowid %lld out of order (min less than parent max of %lld)",
- nMinKey, pnParentMaxKey );
- }
- }
- }
-
- /* Check for complete coverage of the page
- */
- data = pPage.aData;
- hdr = pPage.hdrOffset;
- hit = sqlite3Malloc( pBt.pageSize );
- //if( hit==null ){
- // pCheck.mallocFailed = 1;
- //}else
- {
- int contentOffset = get2byteNotZero( data, hdr + 5 );
- Debug.Assert( contentOffset <= usableSize ); /* Enforced by btreeInitPage() */
- Array.Clear( hit, contentOffset, usableSize - contentOffset );//memset(hit+contentOffset, 0, usableSize-contentOffset);
- for ( int iLoop = contentOffset - 1; iLoop >= 0; iLoop-- )
- hit[iLoop] = 1;//memset(hit, 1, contentOffset);
- nCell = get2byte( data, hdr + 3 );
- cellStart = hdr + 12 - 4 * pPage.leaf;
- for ( i = 0; i < nCell; i++ )
- {
- int pc = get2byte( data, cellStart + i * 2 );
- u32 size = 65536;
- int j;
- if ( pc <= usableSize - 4 )
- {
- size = cellSizePtr( pPage, data, pc );
- }
- if ( (int)( pc + size - 1 ) >= usableSize )
- {
- checkAppendMsg( pCheck, "",
- "Corruption detected in cell %d on page %d", i, iPage );
- }
- else
- {
- for ( j = (int)( pc + size - 1 ); j >= pc; j-- )
- hit[j]++;
- }
- }
- i = get2byte( data, hdr + 1 );
- while ( i > 0 )
- {
- int size, j;
- Debug.Assert( i <= usableSize - 4 ); /* Enforced by btreeInitPage() */
- size = get2byte( data, i + 2 );
- Debug.Assert( i + size <= usableSize ); /* Enforced by btreeInitPage() */
- for ( j = i + size - 1; j >= i; j-- )
- hit[j]++;
- j = get2byte( data, i );
- Debug.Assert( j == 0 || j > i + size ); /* Enforced by btreeInitPage() */
- Debug.Assert( j <= usableSize - 4 ); /* Enforced by btreeInitPage() */
- i = j;
- }
- for ( i = cnt = 0; i < usableSize; i++ )
- {
- if ( hit[i] == 0 )
- {
- cnt++;
- }
- else if ( hit[i] > 1 )
- {
- checkAppendMsg( pCheck, "",
- "Multiple uses for byte %d of page %d", i, iPage );
- break;
- }
- }
- if ( cnt != data[hdr + 7] )
- {
- checkAppendMsg( pCheck, "",
- "Fragmentation of %d bytes reported as %d on page %d",
- cnt, data[hdr + 7], iPage );
- }
- }
- sqlite3PageFree( ref hit );
- releasePage( pPage );
- return depth + 1;
-}
+ // checkTreePage(pCheck, pgno, zContext, NULL, !pPage->nCell ? NULL : &nMaxKey);
+ if (0 == pPage.nCell)
+ checkTreePage(pCheck, pgno, zContext.ToString(), ref refNULL, ref refNULL, null, null);
+ else
+ checkTreePage(pCheck, pgno, zContext.ToString(), ref refNULL, ref nMaxKey, null, pCheck);
+ }
+
+ /* For intKey leaf pages, check that the min/max keys are in order
+ ** with any left/parent/right pages.
+ */
+ if (pPage.leaf != 0 && pPage.intKey != 0) {
+ /* if we are a left child page */
+ if (_pnParentMinKey != null) {
+ /* if we are the left most child page */
+ if (_pnParentMaxKey == null) {
+ if (nMaxKey > pnParentMinKey) {
+ checkAppendMsg(pCheck, zContext,
+ "Rowid %lld out of order (max larger than parent min of %lld)",
+ nMaxKey, pnParentMinKey);
+ }
+ } else {
+ if (nMinKey <= pnParentMinKey) {
+ checkAppendMsg(pCheck, zContext,
+ "Rowid %lld out of order (min less than parent min of %lld)",
+ nMinKey, pnParentMinKey);
+ }
+ if (nMaxKey > pnParentMaxKey) {
+ checkAppendMsg(pCheck, zContext,
+ "Rowid %lld out of order (max larger than parent max of %lld)",
+ nMaxKey, pnParentMaxKey);
+ }
+ pnParentMinKey = nMaxKey;
+ }
+ /* else if we're a right child page */
+ } else if (_pnParentMaxKey != null) {
+ if (nMinKey <= pnParentMaxKey) {
+ checkAppendMsg(pCheck, zContext,
+ "Rowid %lld out of order (min less than parent max of %lld)",
+ nMinKey, pnParentMaxKey);
+ }
+ }
+ }
+
+ /* Check for complete coverage of the page
+ */
+ data = pPage.aData;
+ hdr = pPage.hdrOffset;
+ hit = sqlite3Malloc(pBt.pageSize);
+ //if( hit==null ){
+ // pCheck.mallocFailed = 1;
+ //}else
+ {
+ int contentOffset = get2byteNotZero(data, hdr + 5);
+ Debug.Assert(contentOffset <= usableSize); /* Enforced by btreeInitPage() */
+ Array.Clear(hit, contentOffset, usableSize - contentOffset);//memset(hit+contentOffset, 0, usableSize-contentOffset);
+ for (int iLoop = contentOffset - 1; iLoop >= 0; iLoop--)
+ hit[iLoop] = 1;//memset(hit, 1, contentOffset);
+ nCell = get2byte(data, hdr + 3);
+ cellStart = hdr + 12 - 4 * pPage.leaf;
+ for (i = 0; i < nCell; i++) {
+ int pc = get2byte(data, cellStart + i * 2);
+ u32 size = 65536;
+ int j;
+ if (pc <= usableSize - 4) {
+ size = cellSizePtr(pPage, data, pc);
+ }
+ if ((int)(pc + size - 1) >= usableSize) {
+ checkAppendMsg(pCheck, "",
+ "Corruption detected in cell %d on page %d", i, iPage);
+ } else {
+ for (j = (int)(pc + size - 1); j >= pc; j--)
+ hit[j]++;
+ }
+ }
+ i = get2byte(data, hdr + 1);
+ while (i > 0) {
+ int size, j;
+ Debug.Assert(i <= usableSize - 4); /* Enforced by btreeInitPage() */
+ size = get2byte(data, i + 2);
+ Debug.Assert(i + size <= usableSize); /* Enforced by btreeInitPage() */
+ for (j = i + size - 1; j >= i; j--)
+ hit[j]++;
+ j = get2byte(data, i);
+ Debug.Assert(j == 0 || j > i + size); /* Enforced by btreeInitPage() */
+ Debug.Assert(j <= usableSize - 4); /* Enforced by btreeInitPage() */
+ i = j;
+ }
+ for (i = cnt = 0; i < usableSize; i++) {
+ if (hit[i] == 0) {
+ cnt++;
+ } else if (hit[i] > 1) {
+ checkAppendMsg(pCheck, "",
+ "Multiple uses for byte %d of page %d", i, iPage);
+ break;
+ }
+ }
+ if (cnt != data[hdr + 7]) {
+ checkAppendMsg(pCheck, "",
+ "Fragmentation of %d bytes reported as %d on page %d",
+ cnt, data[hdr + 7], iPage);
+ }
+ }
+ sqlite3PageFree(ref hit);
+ releasePage(pPage);
+ return depth + 1;
+ }
#endif //* SQLITE_OMIT_INTEGRITY_CHECK */
#if !SQLITE_OMIT_INTEGRITY_CHECK
-/*
-** This routine does a complete check of the given BTree file. aRoot[] is
-** an array of pages numbers were each page number is the root page of
-** a table. nRoot is the number of entries in aRoot.
-**
-** A read-only or read-write transaction must be opened before calling
-** this function.
-**
-** Write the number of error seen in pnErr. Except for some memory
-** allocation errors, an error message held in memory obtained from
-** malloc is returned if pnErr is non-zero. If pnErr==null then NULL is
-** returned. If a memory allocation error occurs, NULL is returned.
-*/
-static string sqlite3BtreeIntegrityCheck(
-Btree p, /* The btree to be checked */
-int[] aRoot, /* An array of root pages numbers for individual trees */
-int nRoot, /* Number of entries in aRoot[] */
-int mxErr, /* Stop reporting errors after this many */
-ref int pnErr /* Write number of errors seen to this variable */
-)
-{
- Pgno i;
- int nRef;
- IntegrityCk sCheck = new IntegrityCk();
- BtShared pBt = p.pBt;
-
- sqlite3BtreeEnter( p );
- Debug.Assert( p.inTrans > TRANS_NONE && pBt.inTransaction > TRANS_NONE );
- nRef = sqlite3PagerRefcount( pBt.pPager );
- sCheck.pBt = pBt;
- sCheck.pPager = pBt.pPager;
- sCheck.nPage = btreePagecount( sCheck.pBt );
- sCheck.mxErr = mxErr;
- sCheck.nErr = 0;
- //sCheck.mallocFailed = 0;
- pnErr = 0;
- if ( sCheck.nPage == 0 )
- {
- sqlite3BtreeLeave( p );
- return "";
- }
- sCheck.anRef = sqlite3Malloc( sCheck.anRef, (int)sCheck.nPage + 1 );
- //if( !sCheck.anRef ){
- // pnErr = 1;
- // sqlite3BtreeLeave(p);
- // return 0;
- //}
- // for (i = 0; i <= sCheck.nPage; i++) { sCheck.anRef[i] = 0; }
- i = PENDING_BYTE_PAGE( pBt );
- if ( i <= sCheck.nPage )
- {
- sCheck.anRef[i] = 1;
- }
- sqlite3StrAccumInit( sCheck.errMsg, null, 1000, 20000 );
- //sCheck.errMsg.useMalloc = 2;
-
- /* Check the integrity of the freelist
- */
- checkList( sCheck, 1, (int)sqlite3Get4byte( pBt.pPage1.aData, 32 ),
- (int)sqlite3Get4byte( pBt.pPage1.aData, 36 ), "Main freelist: " );
-
- /* Check all the tables.
- */
- for ( i = 0; (int)i < nRoot && sCheck.mxErr != 0; i++ )
- {
- if ( aRoot[i] == 0 )
- continue;
+ /*
+ ** This routine does a complete check of the given BTree file. aRoot[] is
+ ** an array of pages numbers were each page number is the root page of
+ ** a table. nRoot is the number of entries in aRoot.
+ **
+ ** A read-only or read-write transaction must be opened before calling
+ ** this function.
+ **
+ ** Write the number of error seen in pnErr. Except for some memory
+ ** allocation errors, an error message held in memory obtained from
+ ** malloc is returned if pnErr is non-zero. If pnErr==null then NULL is
+ ** returned. If a memory allocation error occurs, NULL is returned.
+ */
+ static string sqlite3BtreeIntegrityCheck(
+ Btree p, /* The btree to be checked */
+ int[] aRoot, /* An array of root pages numbers for individual trees */
+ int nRoot, /* Number of entries in aRoot[] */
+ int mxErr, /* Stop reporting errors after this many */
+ ref int pnErr /* Write number of errors seen to this variable */
+ ) {
+ Pgno i;
+ int nRef;
+ IntegrityCk sCheck = new IntegrityCk();
+ BtShared pBt = p.pBt;
+
+ sqlite3BtreeEnter(p);
+ Debug.Assert(p.inTrans > TRANS_NONE && pBt.inTransaction > TRANS_NONE);
+ nRef = sqlite3PagerRefcount(pBt.pPager);
+ sCheck.pBt = pBt;
+ sCheck.pPager = pBt.pPager;
+ sCheck.nPage = btreePagecount(sCheck.pBt);
+ sCheck.mxErr = mxErr;
+ sCheck.nErr = 0;
+ //sCheck.mallocFailed = 0;
+ pnErr = 0;
+ if (sCheck.nPage == 0) {
+ sqlite3BtreeLeave(p);
+ return "";
+ }
+ sCheck.anRef = sqlite3Malloc(sCheck.anRef, (int)sCheck.nPage + 1);
+ //if( !sCheck.anRef ){
+ // pnErr = 1;
+ // sqlite3BtreeLeave(p);
+ // return 0;
+ //}
+ // for (i = 0; i <= sCheck.nPage; i++) { sCheck.anRef[i] = 0; }
+ i = PENDING_BYTE_PAGE(pBt);
+ if (i <= sCheck.nPage) {
+ sCheck.anRef[i] = 1;
+ }
+ sqlite3StrAccumInit(sCheck.errMsg, null, 1000, 20000);
+ //sCheck.errMsg.useMalloc = 2;
+
+ /* Check the integrity of the freelist
+ */
+ checkList(sCheck, 1, (int)sqlite3Get4byte(pBt.pPage1.aData, 32),
+ (int)sqlite3Get4byte(pBt.pPage1.aData, 36), "Main freelist: ");
+
+ /* Check all the tables.
+ */
+ for (i = 0; (int)i < nRoot && sCheck.mxErr != 0; i++) {
+ if (aRoot[i] == 0)
+ continue;
#if !SQLITE_OMIT_AUTOVACUUM
- if ( pBt.autoVacuum && aRoot[i] > 1 )
- {
- checkPtrmap( sCheck, (u32)aRoot[i], PTRMAP_ROOTPAGE, 0, "" );
- }
+ if (pBt.autoVacuum && aRoot[i] > 1) {
+ checkPtrmap(sCheck, (u32)aRoot[i], PTRMAP_ROOTPAGE, 0, "");
+ }
#endif
- checkTreePage( sCheck, aRoot[i], "List of tree roots: ", ref refNULL, ref refNULL, null, null );
- }
+ checkTreePage(sCheck, aRoot[i], "List of tree roots: ", ref refNULL, ref refNULL, null, null);
+ }
- /* Make sure every page in the file is referenced
- */
- for ( i = 1; i <= sCheck.nPage && sCheck.mxErr != 0; i++ )
- {
+ /* Make sure every page in the file is referenced
+ */
+ for (i = 1; i <= sCheck.nPage && sCheck.mxErr != 0; i++) {
#if SQLITE_OMIT_AUTOVACUUM
if( sCheck.anRef[i]==null ){
checkAppendMsg(sCheck, 0, "Page %d is never used", i);
}
#else
- /* If the database supports auto-vacuum, make sure no tables contain
-** references to pointer-map pages.
-*/
- if ( sCheck.anRef[i] == 0 &&
- ( PTRMAP_PAGENO( pBt, i ) != i || !pBt.autoVacuum ) )
- {
- checkAppendMsg( sCheck, "", "Page %d is never used", i );
- }
- if ( sCheck.anRef[i] != 0 &&
- ( PTRMAP_PAGENO( pBt, i ) == i && pBt.autoVacuum ) )
- {
- checkAppendMsg( sCheck, "", "Pointer map page %d is referenced", i );
- }
+ /* If the database supports auto-vacuum, make sure no tables contain
+ ** references to pointer-map pages.
+ */
+ if (sCheck.anRef[i] == 0 &&
+ (PTRMAP_PAGENO(pBt, i) != i || !pBt.autoVacuum)) {
+ checkAppendMsg(sCheck, "", "Page %d is never used", i);
+ }
+ if (sCheck.anRef[i] != 0 &&
+ (PTRMAP_PAGENO(pBt, i) == i && pBt.autoVacuum)) {
+ checkAppendMsg(sCheck, "", "Pointer map page %d is referenced", i);
+ }
#endif
- }
-
- /* Make sure this analysis did not leave any unref() pages.
- ** This is an internal consistency check; an integrity check
- ** of the integrity check.
- */
- if ( NEVER( nRef != sqlite3PagerRefcount( pBt.pPager ) ) )
- {
- checkAppendMsg( sCheck, "",
- "Outstanding page count goes from %d to %d during this analysis",
- nRef, sqlite3PagerRefcount( pBt.pPager )
- );
- }
-
- /* Clean up and report errors.
- */
- sqlite3BtreeLeave( p );
- sCheck.anRef = null;// sqlite3_free( ref sCheck.anRef );
- //if( sCheck.mallocFailed ){
- // sqlite3StrAccumReset(sCheck.errMsg);
- // pnErr = sCheck.nErr+1;
- // return 0;
- //}
- pnErr = sCheck.nErr;
- if ( sCheck.nErr == 0 )
- sqlite3StrAccumReset( sCheck.errMsg );
- return sqlite3StrAccumFinish( sCheck.errMsg );
-}
+ }
+
+ /* Make sure this analysis did not leave any unref() pages.
+ ** This is an internal consistency check; an integrity check
+ ** of the integrity check.
+ */
+ if (NEVER(nRef != sqlite3PagerRefcount(pBt.pPager))) {
+ checkAppendMsg(sCheck, "",
+ "Outstanding page count goes from %d to %d during this analysis",
+ nRef, sqlite3PagerRefcount(pBt.pPager)
+ );
+ }
+
+ /* Clean up and report errors.
+ */
+ sqlite3BtreeLeave(p);
+ sCheck.anRef = null;// sqlite3_free( ref sCheck.anRef );
+ //if( sCheck.mallocFailed ){
+ // sqlite3StrAccumReset(sCheck.errMsg);
+ // pnErr = sCheck.nErr+1;
+ // return 0;
+ //}
+ pnErr = sCheck.nErr;
+ if (sCheck.nErr == 0)
+ sqlite3StrAccumReset(sCheck.errMsg);
+ return sqlite3StrAccumFinish(sCheck.errMsg);
+ }
#endif //* SQLITE_OMIT_INTEGRITY_CHECK */
-/*
-** Return the full pathname of the underlying database file.
-**
-** The pager filename is invariant as long as the pager is
-** open so it is safe to access without the BtShared mutex.
-*/
-static string sqlite3BtreeGetFilename( Btree p )
-{
- Debug.Assert( p.pBt.pPager != null );
- return sqlite3PagerFilename( p.pBt.pPager );
-}
+ /*
+ ** Return the full pathname of the underlying database file.
+ **
+ ** The pager filename is invariant as long as the pager is
+ ** open so it is safe to access without the BtShared mutex.
+ */
+ static string sqlite3BtreeGetFilename(Btree p) {
+ Debug.Assert(p.pBt.pPager != null);
+ return sqlite3PagerFilename(p.pBt.pPager);
+ }
-/*
-** Return the pathname of the journal file for this database. The return
-** value of this routine is the same regardless of whether the journal file
-** has been created or not.
-**
-** The pager journal filename is invariant as long as the pager is
-** open so it is safe to access without the BtShared mutex.
-*/
-static string sqlite3BtreeGetJournalname( Btree p )
-{
- Debug.Assert( p.pBt.pPager != null );
- return sqlite3PagerJournalname( p.pBt.pPager );
-}
+ /*
+ ** Return the pathname of the journal file for this database. The return
+ ** value of this routine is the same regardless of whether the journal file
+ ** has been created or not.
+ **
+ ** The pager journal filename is invariant as long as the pager is
+ ** open so it is safe to access without the BtShared mutex.
+ */
+ static string sqlite3BtreeGetJournalname(Btree p) {
+ Debug.Assert(p.pBt.pPager != null);
+ return sqlite3PagerJournalname(p.pBt.pPager);
+ }
-/*
-** Return non-zero if a transaction is active.
-*/
-static bool sqlite3BtreeIsInTrans( Btree p )
-{
- Debug.Assert( p == null || sqlite3_mutex_held( p.db.mutex ) );
- return ( p != null && ( p.inTrans == TRANS_WRITE ) );
-}
+ /*
+ ** Return non-zero if a transaction is active.
+ */
+ static bool sqlite3BtreeIsInTrans(Btree p) {
+ Debug.Assert(p == null || sqlite3_mutex_held(p.db.mutex));
+ return (p != null && (p.inTrans == TRANS_WRITE));
+ }
#if !SQLITE_OMIT_WAL
/*
@@ -9365,71 +8499,66 @@ static bool sqlite3BtreeIsInTrans( Btree p )
}
#endif
-/*
-** Return non-zero if a read (or write) transaction is active.
-*/
-static bool sqlite3BtreeIsInReadTrans( Btree p )
-{
- Debug.Assert( p != null );
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- return p.inTrans != TRANS_NONE;
-}
+ /*
+ ** Return non-zero if a read (or write) transaction is active.
+ */
+ static bool sqlite3BtreeIsInReadTrans(Btree p) {
+ Debug.Assert(p != null);
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ return p.inTrans != TRANS_NONE;
+ }
-static bool sqlite3BtreeIsInBackup( Btree p )
-{
- Debug.Assert( p != null );
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- return p.nBackup != 0;
-}
+ static bool sqlite3BtreeIsInBackup(Btree p) {
+ Debug.Assert(p != null);
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ return p.nBackup != 0;
+ }
-/*
-** This function returns a pointer to a blob of memory associated with
-** a single shared-btree. The memory is used by client code for its own
-** purposes (for example, to store a high-level schema associated with
-** the shared-btree). The btree layer manages reference counting issues.
-**
-** The first time this is called on a shared-btree, nBytes bytes of memory
-** are allocated, zeroed, and returned to the caller. For each subsequent
-** call the nBytes parameter is ignored and a pointer to the same blob
-** of memory returned.
-**
-** If the nBytes parameter is 0 and the blob of memory has not yet been
-** allocated, a null pointer is returned. If the blob has already been
-** allocated, it is returned as normal.
-**
-** Just before the shared-btree is closed, the function passed as the
-** xFree argument when the memory allocation was made is invoked on the
-** blob of allocated memory. The xFree function should not call sqlite3_free()
-** on the memory, the btree layer does that.
-*/
-static Schema sqlite3BtreeSchema( Btree p, int nBytes, dxFreeSchema xFree )
-{
- BtShared pBt = p.pBt;
- sqlite3BtreeEnter( p );
- if ( null == pBt.pSchema && nBytes != 0 )
- {
- pBt.pSchema = new Schema();//sqlite3DbMallocZero(0, nBytes);
- pBt.xFreeSchema = xFree;
- }
- sqlite3BtreeLeave( p );
- return pBt.pSchema;
-}
+ /*
+ ** This function returns a pointer to a blob of memory associated with
+ ** a single shared-btree. The memory is used by client code for its own
+ ** purposes (for example, to store a high-level schema associated with
+ ** the shared-btree). The btree layer manages reference counting issues.
+ **
+ ** The first time this is called on a shared-btree, nBytes bytes of memory
+ ** are allocated, zeroed, and returned to the caller. For each subsequent
+ ** call the nBytes parameter is ignored and a pointer to the same blob
+ ** of memory returned.
+ **
+ ** If the nBytes parameter is 0 and the blob of memory has not yet been
+ ** allocated, a null pointer is returned. If the blob has already been
+ ** allocated, it is returned as normal.
+ **
+ ** Just before the shared-btree is closed, the function passed as the
+ ** xFree argument when the memory allocation was made is invoked on the
+ ** blob of allocated memory. The xFree function should not call sqlite3_free()
+ ** on the memory, the btree layer does that.
+ */
+ static Schema sqlite3BtreeSchema(Btree p, int nBytes, dxFreeSchema xFree) {
+ BtShared pBt = p.pBt;
+ sqlite3BtreeEnter(p);
+ if (null == pBt.pSchema && nBytes != 0) {
+ pBt.pSchema = new Schema();//sqlite3DbMallocZero(0, nBytes);
+ pBt.xFreeSchema = xFree;
+ }
+ sqlite3BtreeLeave(p);
+ return pBt.pSchema;
+ }
-/*
-** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
-** btree as the argument handle holds an exclusive lock on the
-** sqlite_master table. Otherwise SQLITE_OK.
-*/
-static int sqlite3BtreeSchemaLocked( Btree p )
-{
- int rc;
- Debug.Assert( sqlite3_mutex_held( p.db.mutex ) );
- sqlite3BtreeEnter( p );
- rc = querySharedCacheTableLock( p, MASTER_ROOT, READ_LOCK );
- Debug.Assert( rc == SQLITE_OK || rc == SQLITE_LOCKED_SHAREDCACHE );
- sqlite3BtreeLeave( p );
- return rc;
-}
+ /*
+ ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
+ ** btree as the argument handle holds an exclusive lock on the
+ ** sqlite_master table. Otherwise SQLITE_OK.
+ */
+ static int sqlite3BtreeSchemaLocked(Btree p) {
+ int rc;
+ Debug.Assert(sqlite3_mutex_held(p.db.mutex));
+ sqlite3BtreeEnter(p);
+ rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
+ Debug.Assert(rc == SQLITE_OK || rc == SQLITE_LOCKED_SHAREDCACHE);
+ sqlite3BtreeLeave(p);
+ return rc;
+ }
#if !SQLITE_OMIT_SHARED_CACHE
@@ -9519,45 +8648,40 @@ static void sqlite3BtreeCacheOverflow(BtCursor pCur){
}
#endif
-/*
-** Set both the "read version" (single byte at byte offset 18) and
-** "write version" (single byte at byte offset 19) fields in the database
-** header to iVersion.
-*/
-static int sqlite3BtreeSetVersion( Btree pBtree, int iVersion )
-{
- BtShared pBt = pBtree.pBt;
- int rc; /* Return code */
-
- Debug.Assert( pBtree.inTrans == TRANS_NONE );
- Debug.Assert( iVersion == 1 || iVersion == 2 );
-
- /* If setting the version fields to 1, do not automatically open the
- ** WAL connection, even if the version fields are currently set to 2.
- */
- pBt.doNotUseWAL = iVersion == 1;
-
- rc = sqlite3BtreeBeginTrans( pBtree, 0 );
- if ( rc == SQLITE_OK )
- {
- u8[] aData = pBt.pPage1.aData;
- if ( aData[18] != (u8)iVersion || aData[19] != (u8)iVersion )
- {
- rc = sqlite3BtreeBeginTrans( pBtree, 2 );
- if ( rc == SQLITE_OK )
- {
- rc = sqlite3PagerWrite( pBt.pPage1.pDbPage );
- if ( rc == SQLITE_OK )
- {
- aData[18] = (u8)iVersion;
- aData[19] = (u8)iVersion;
- }
- }
- }
- }
+ /*
+ ** Set both the "read version" (single byte at byte offset 18) and
+ ** "write version" (single byte at byte offset 19) fields in the database
+ ** header to iVersion.
+ */
+ static int sqlite3BtreeSetVersion(Btree pBtree, int iVersion) {
+ BtShared pBt = pBtree.pBt;
+ int rc; /* Return code */
+
+ Debug.Assert(pBtree.inTrans == TRANS_NONE);
+ Debug.Assert(iVersion == 1 || iVersion == 2);
+
+ /* If setting the version fields to 1, do not automatically open the
+ ** WAL connection, even if the version fields are currently set to 2.
+ */
+ pBt.doNotUseWAL = iVersion == 1;
+
+ rc = sqlite3BtreeBeginTrans(pBtree, 0);
+ if (rc == SQLITE_OK) {
+ u8[] aData = pBt.pPage1.aData;
+ if (aData[18] != (u8)iVersion || aData[19] != (u8)iVersion) {
+ rc = sqlite3BtreeBeginTrans(pBtree, 2);
+ if (rc == SQLITE_OK) {
+ rc = sqlite3PagerWrite(pBt.pPage1.pDbPage);
+ if (rc == SQLITE_OK) {
+ aData[18] = (u8)iVersion;
+ aData[19] = (u8)iVersion;
+ }
+ }
+ }
+ }
- pBt.doNotUseWAL = false;
- return rc;
-}
- }
+ pBt.doNotUseWAL = false;
+ return rc;
+ }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/build_c.cs b/Src/IronPython.SQLite/c#sqlite/build_c.cs
index 0050bf2f0..754334f1c 100644
--- a/Src/IronPython.SQLite/c#sqlite/build_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/build_c.cs
@@ -8,8 +8,6 @@
using u16 = System.UInt16;
using u32 = System.UInt32;
-using Pgno = System.UInt32;
-
/*
** The yDbMask datatype for the bitmask of all attached databases.
*/
@@ -18,55 +16,52 @@
using yDbMask = System.Int64;
#else
// typedef unsigned int yDbMask;
-using yDbMask = System.Int32;
+using yDbMask = System.Int32;
#endif
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This file contains C code routines that are called by the SQLite parser
- ** when syntax rules are reduced. The routines in this file handle the
- ** following kinds of SQL syntax:
- **
- ** CREATE TABLE
- ** DROP TABLE
- ** CREATE INDEX
- ** DROP INDEX
- ** creating ID lists
- ** BEGIN TRANSACTION
- ** COMMIT
- ** ROLLBACK
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains C code routines that are called by the SQLite parser
+ ** when syntax rules are reduced. The routines in this file handle the
+ ** following kinds of SQL syntax:
+ **
+ ** CREATE TABLE
+ ** DROP TABLE
+ ** CREATE INDEX
+ ** DROP INDEX
+ ** creating ID lists
+ ** BEGIN TRANSACTION
+ ** COMMIT
+ ** ROLLBACK
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
- /*
- ** This routine is called when a new SQL statement is beginning to
- ** be parsed. Initialize the pParse structure as needed.
- */
- static void sqlite3BeginParse( Parse pParse, int explainFlag )
- {
- pParse.explain = (byte)explainFlag;
- pParse.nVar = 0;
- }
+ /*
+ ** This routine is called when a new SQL statement is beginning to
+ ** be parsed. Initialize the pParse structure as needed.
+ */
+ static void sqlite3BeginParse(Parse pParse, int explainFlag) {
+ pParse.explain = (byte)explainFlag;
+ pParse.nVar = 0;
+ }
#if !SQLITE_OMIT_SHARED_CACHE
/*
@@ -154,496 +149,450 @@ static void codeTableLocks( Parse pParse )
}
}
#else
- // #define codeTableLocks(x)
- static void codeTableLocks( Parse pParse )
- {
- }
+ // #define codeTableLocks(x)
+ static void codeTableLocks(Parse pParse) {
+ }
#endif
- /*
-** This routine is called after a single SQL statement has been
-** parsed and a VDBE program to execute that statement has been
-** prepared. This routine puts the finishing touches on the
-** VDBE program and resets the pParse structure for the next
-** parse.
-**
-** Note that if an error occurred, it might be the case that
-** no VDBE code was generated.
-*/
- static void sqlite3FinishCoding( Parse pParse )
- {
- sqlite3 db;
- Vdbe v;
-
- db = pParse.db;
- // if ( db.mallocFailed != 0 ) return;
- if ( pParse.nested != 0 )
- return;
- if ( pParse.nErr != 0 )
- return;
-
- /* Begin by generating some termination code at the end of the
- ** vdbe program
- */
- v = sqlite3GetVdbe( pParse );
- Debug.Assert( 0 == pParse.isMultiWrite
-#if SQLITE_DEBUG
- || sqlite3VdbeAssertMayAbort( v, pParse.mayAbort ) != 0
+ /*
+ ** This routine is called after a single SQL statement has been
+ ** parsed and a VDBE program to execute that statement has been
+ ** prepared. This routine puts the finishing touches on the
+ ** VDBE program and resets the pParse structure for the next
+ ** parse.
+ **
+ ** Note that if an error occurred, it might be the case that
+ ** no VDBE code was generated.
+ */
+ static void sqlite3FinishCoding(Parse pParse) {
+ sqlite3 db;
+ Vdbe v;
+
+ db = pParse.db;
+ // if ( db.mallocFailed != 0 ) return;
+ if (pParse.nested != 0)
+ return;
+ if (pParse.nErr != 0)
+ return;
+
+ /* Begin by generating some termination code at the end of the
+ ** vdbe program
+ */
+ v = sqlite3GetVdbe(pParse);
+ Debug.Assert(0 == pParse.isMultiWrite
+#if SQLITE_DEBUG
+ || sqlite3VdbeAssertMayAbort(v, pParse.mayAbort) != 0
#endif
- );
- if ( v != null )
- {
- sqlite3VdbeAddOp0( v, OP_Halt );
-
- /* The cookie mask contains one bit for each database file open.
- ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
- ** set for each database that is used. Generate code to start a
- ** transaction on each used database and to verify the schema cookie
- ** on each used database.
- */
- if ( pParse.cookieGoto > 0 )
- {
- u32 mask;
- int iDb;
- sqlite3VdbeJumpHere( v, pParse.cookieGoto - 1 );
- for ( iDb = 0, mask = 1; iDb < db.nDb; mask <<= 1, iDb++ )
- {
- if ( ( mask & pParse.cookieMask ) == 0 )
- continue;
- sqlite3VdbeUsesBtree( v, iDb );
- sqlite3VdbeAddOp2( v, OP_Transaction, iDb, ( mask & pParse.writeMask ) != 0 );
- if ( db.init.busy == 0 )
- {
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- sqlite3VdbeAddOp3( v, OP_VerifyCookie,
- iDb, pParse.cookieValue[iDb],
- (int)db.aDb[iDb].pSchema.iGeneration );
- }
- }
+ );
+ if (v != null) {
+ sqlite3VdbeAddOp0(v, OP_Halt);
+
+ /* The cookie mask contains one bit for each database file open.
+ ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
+ ** set for each database that is used. Generate code to start a
+ ** transaction on each used database and to verify the schema cookie
+ ** on each used database.
+ */
+ if (pParse.cookieGoto > 0) {
+ u32 mask;
+ int iDb;
+ sqlite3VdbeJumpHere(v, pParse.cookieGoto - 1);
+ for (iDb = 0, mask = 1; iDb < db.nDb; mask <<= 1, iDb++) {
+ if ((mask & pParse.cookieMask) == 0)
+ continue;
+ sqlite3VdbeUsesBtree(v, iDb);
+ sqlite3VdbeAddOp2(v, OP_Transaction, iDb, (mask & pParse.writeMask) != 0);
+ if (db.init.busy == 0) {
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ sqlite3VdbeAddOp3(v, OP_VerifyCookie,
+ iDb, pParse.cookieValue[iDb],
+ (int)db.aDb[iDb].pSchema.iGeneration);
+ }
+ }
#if !SQLITE_OMIT_VIRTUALTABLE
- {
- int i;
- for ( i = 0; i < pParse.nVtabLock; i++ )
- {
- VTable vtab = sqlite3GetVTable( db, pParse.apVtabLock[i] );
- sqlite3VdbeAddOp4( v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB );
- }
- pParse.nVtabLock = 0;
- }
+ {
+ int i;
+ for (i = 0; i < pParse.nVtabLock; i++) {
+ VTable vtab = sqlite3GetVTable(db, pParse.apVtabLock[i]);
+ sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
+ }
+ pParse.nVtabLock = 0;
+ }
#endif
- /* Once all the cookies have been verified and transactions opened,
-** obtain the required table-locks. This is a no-op unless the
-** shared-cache feature is enabled.
-*/
- codeTableLocks( pParse );
-
- /* Initialize any AUTOINCREMENT data structures required.
+ /* Once all the cookies have been verified and transactions opened,
+ ** obtain the required table-locks. This is a no-op unless the
+ ** shared-cache feature is enabled.
*/
- sqlite3AutoincrementBegin( pParse );
+ codeTableLocks(pParse);
- /* Finally, jump back to the beginning of the executable code. */
- sqlite3VdbeAddOp2( v, OP_Goto, 0, pParse.cookieGoto );
- }
- }
+ /* Initialize any AUTOINCREMENT data structures required.
+ */
+ sqlite3AutoincrementBegin(pParse);
+ /* Finally, jump back to the beginning of the executable code. */
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse.cookieGoto);
+ }
+ }
- /* Get the VDBE program ready for execution
- */
- if ( v != null && ALWAYS( pParse.nErr == 0 ) /* && 0 == db.mallocFailed */ )
- {
-#if SQLITE_DEBUG && !SQLITE_WINRT
- TextWriter trace = ( db.flags & SQLITE_VdbeTrace ) != 0 ? Console.Out : null;
- sqlite3VdbeTrace( v, trace );
-#endif
- Debug.Assert( pParse.iCacheLevel == 0 ); /* Disables and re-enables match */
- /* A minimum of one cursor is required if autoincrement is used
- * See ticket [a696379c1f08866] */
- if ( pParse.pAinc != null && pParse.nTab == 0 )
- pParse.nTab = 1;
- sqlite3VdbeMakeReady( v, pParse);
- pParse.rc = SQLITE_DONE;
- pParse.colNamesSet = 0;
- }
- else
- {
- pParse.rc = SQLITE_ERROR;
- }
- pParse.nTab = 0;
- pParse.nMem = 0;
- pParse.nSet = 0;
- pParse.nVar = 0;
- pParse.cookieMask = 0;
- pParse.cookieGoto = 0;
- }
- /*
- ** Run the parser and code generator recursively in order to generate
- ** code for the SQL statement given onto the end of the pParse context
- ** currently under construction. When the parser is run recursively
- ** this way, the final OP_Halt is not appended and other initialization
- ** and finalization steps are omitted because those are handling by the
- ** outermost parser.
- **
- ** Not everything is nestable. This facility is designed to permit
- ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
- ** care if you decide to try to use this routine for some other purposes.
- */
- static void sqlite3NestedParse( Parse pParse, string zFormat, params object[] ap )
- {
- string zSql; // string zSql;
- string zErrMsg = "";// char* zErrMsg = 0;
- sqlite3 db = pParse.db;
-
- //# define SAVE_SZ (Parse.Length - offsetof(Parse,nVar))
- // char saveBuf[SAVE_SZ];
-
- if ( pParse.nErr != 0 )
- return;
- Debug.Assert( pParse.nested < 10 ); /* Nesting should only be of limited depth */
- // va_list ap;
- lock ( lock_va_list )
- {
- va_start( ap, zFormat );
- zSql = sqlite3VMPrintf( db, zFormat, ap );
- va_end( ref ap );
- }
- //if( zSql=="" ){
- // return; /* A malloc must have failed */
- //}
- lock ( nestingLock )
- {
- pParse.nested++;
- pParse.SaveMembers(); // memcpy(saveBuf, pParse.nVar, SAVE_SZ);
- pParse.ResetMembers(); // memset(pParse.nVar, 0, SAVE_SZ);
- sqlite3RunParser( pParse, zSql, ref zErrMsg );
- sqlite3DbFree( db, ref zErrMsg );
- sqlite3DbFree( db, ref zSql );
- pParse.RestoreMembers(); // memcpy(pParse.nVar, saveBuf, SAVE_SZ);
- pParse.nested--;
- }
- }
- static Object nestingLock = new Object();
+ /* Get the VDBE program ready for execution
+ */
+ if (v != null && ALWAYS(pParse.nErr == 0) /* && 0 == db.mallocFailed */ ) {
+#if SQLITE_DEBUG && !SQLITE_WINRT
+ TextWriter trace = (db.flags & SQLITE_VdbeTrace) != 0 ? Console.Out : null;
+ sqlite3VdbeTrace(v, trace);
+#endif
+ Debug.Assert(pParse.iCacheLevel == 0); /* Disables and re-enables match */
+ /* A minimum of one cursor is required if autoincrement is used
+ * See ticket [a696379c1f08866] */
+ if (pParse.pAinc != null && pParse.nTab == 0)
+ pParse.nTab = 1;
+ sqlite3VdbeMakeReady(v, pParse);
+ pParse.rc = SQLITE_DONE;
+ pParse.colNamesSet = 0;
+ } else {
+ pParse.rc = SQLITE_ERROR;
+ }
+ pParse.nTab = 0;
+ pParse.nMem = 0;
+ pParse.nSet = 0;
+ pParse.nVar = 0;
+ pParse.cookieMask = 0;
+ pParse.cookieGoto = 0;
+ }
- /*
- ** Locate the in-memory structure that describes a particular database
- ** table given the name of that table and (optionally) the name of the
- ** database containing the table. Return NULL if not found.
- **
- ** If zDatabase is 0, all databases are searched for the table and the
- ** first matching table is returned. (No checking for duplicate table
- ** names is done.) The search order is TEMP first, then MAIN, then any
- ** auxiliary databases added using the ATTACH command.
- **
- ** See also sqlite3LocateTable().
- */
- static Table sqlite3FindTable( sqlite3 db, string zName, string zDatabase )
- {
- Table p = null;
- int i;
- int nName;
- Debug.Assert( zName != null );
- nName = sqlite3Strlen30( zName );
- /* All mutexes are required for schema access. Make sure we hold them. */
- Debug.Assert( zDatabase != null || sqlite3BtreeHoldsAllMutexes( db ) );
- for ( i = OMIT_TEMPDB; i < db.nDb; i++ )
- {
- int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */
- if ( zDatabase != null && !zDatabase.Equals( db.aDb[j].zName, StringComparison.OrdinalIgnoreCase ) )
- continue;
- Debug.Assert( sqlite3SchemaMutexHeld( db, j, null ) );
- p = sqlite3HashFind( db.aDb[j].pSchema.tblHash, zName, nName, (Table)null );
- if ( p != null )
- break;
- }
- return p;
- }
+ /*
+ ** Run the parser and code generator recursively in order to generate
+ ** code for the SQL statement given onto the end of the pParse context
+ ** currently under construction. When the parser is run recursively
+ ** this way, the final OP_Halt is not appended and other initialization
+ ** and finalization steps are omitted because those are handling by the
+ ** outermost parser.
+ **
+ ** Not everything is nestable. This facility is designed to permit
+ ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
+ ** care if you decide to try to use this routine for some other purposes.
+ */
+ static void sqlite3NestedParse(Parse pParse, string zFormat, params object[] ap) {
+ string zSql; // string zSql;
+ string zErrMsg = "";// char* zErrMsg = 0;
+ sqlite3 db = pParse.db;
+
+ //# define SAVE_SZ (Parse.Length - offsetof(Parse,nVar))
+ // char saveBuf[SAVE_SZ];
+
+ if (pParse.nErr != 0)
+ return;
+ Debug.Assert(pParse.nested < 10); /* Nesting should only be of limited depth */
+ // va_list ap;
+ lock (lock_va_list) {
+ va_start(ap, zFormat);
+ zSql = sqlite3VMPrintf(db, zFormat, ap);
+ va_end(ref ap);
+ }
+ //if( zSql=="" ){
+ // return; /* A malloc must have failed */
+ //}
+ lock (nestingLock) {
+ pParse.nested++;
+ pParse.SaveMembers(); // memcpy(saveBuf, pParse.nVar, SAVE_SZ);
+ pParse.ResetMembers(); // memset(pParse.nVar, 0, SAVE_SZ);
+ sqlite3RunParser(pParse, zSql, ref zErrMsg);
+ sqlite3DbFree(db, ref zErrMsg);
+ sqlite3DbFree(db, ref zSql);
+ pParse.RestoreMembers(); // memcpy(pParse.nVar, saveBuf, SAVE_SZ);
+ pParse.nested--;
+ }
+ }
+ static Object nestingLock = new Object();
- /*
- ** Locate the in-memory structure that describes a particular database
- ** table given the name of that table and (optionally) the name of the
- ** database containing the table. Return NULL if not found. Also leave an
- ** error message in pParse.zErrMsg.
- **
- ** The difference between this routine and sqlite3FindTable() is that this
- ** routine leaves an error message in pParse.zErrMsg where
- ** sqlite3FindTable() does not.
- */
- static Table sqlite3LocateTable(
- Parse pParse, /* context in which to report errors */
- int isView, /* True if looking for a VIEW rather than a TABLE */
- string zName, /* Name of the table we are looking for */
- string zDbase /* Name of the database. Might be NULL */
- )
- {
- Table p;
-
- /* Read the database schema. If an error occurs, leave an error message
- ** and code in pParse and return NULL. */
- if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
- {
- return null;
- }
-
- p = sqlite3FindTable( pParse.db, zName, zDbase );
- if ( p == null )
- {
- string zMsg = isView != 0 ? "no such view" : "no such table";
- if ( zDbase != null )
- {
- sqlite3ErrorMsg( pParse, "%s: %s.%s", zMsg, zDbase, zName );
+ /*
+ ** Locate the in-memory structure that describes a particular database
+ ** table given the name of that table and (optionally) the name of the
+ ** database containing the table. Return NULL if not found.
+ **
+ ** If zDatabase is 0, all databases are searched for the table and the
+ ** first matching table is returned. (No checking for duplicate table
+ ** names is done.) The search order is TEMP first, then MAIN, then any
+ ** auxiliary databases added using the ATTACH command.
+ **
+ ** See also sqlite3LocateTable().
+ */
+ static Table sqlite3FindTable(sqlite3 db, string zName, string zDatabase) {
+ Table p = null;
+ int i;
+ int nName;
+ Debug.Assert(zName != null);
+ nName = sqlite3Strlen30(zName);
+ /* All mutexes are required for schema access. Make sure we hold them. */
+ Debug.Assert(zDatabase != null || sqlite3BtreeHoldsAllMutexes(db));
+ for (i = OMIT_TEMPDB; i < db.nDb; i++) {
+ int j = (i < 2) ? i ^ 1 : i; /* Search TEMP before MAIN */
+ if (zDatabase != null && !zDatabase.Equals(db.aDb[j].zName, StringComparison.OrdinalIgnoreCase))
+ continue;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, j, null));
+ p = sqlite3HashFind(db.aDb[j].pSchema.tblHash, zName, nName, (Table)null);
+ if (p != null)
+ break;
+ }
+ return p;
}
- else
- {
- sqlite3ErrorMsg( pParse, "%s: %s", zMsg, zName );
+
+ /*
+ ** Locate the in-memory structure that describes a particular database
+ ** table given the name of that table and (optionally) the name of the
+ ** database containing the table. Return NULL if not found. Also leave an
+ ** error message in pParse.zErrMsg.
+ **
+ ** The difference between this routine and sqlite3FindTable() is that this
+ ** routine leaves an error message in pParse.zErrMsg where
+ ** sqlite3FindTable() does not.
+ */
+ static Table sqlite3LocateTable(
+ Parse pParse, /* context in which to report errors */
+ int isView, /* True if looking for a VIEW rather than a TABLE */
+ string zName, /* Name of the table we are looking for */
+ string zDbase /* Name of the database. Might be NULL */
+ ) {
+ Table p;
+
+ /* Read the database schema. If an error occurs, leave an error message
+ ** and code in pParse and return NULL. */
+ if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
+ return null;
+ }
+
+ p = sqlite3FindTable(pParse.db, zName, zDbase);
+ if (p == null) {
+ string zMsg = isView != 0 ? "no such view" : "no such table";
+ if (zDbase != null) {
+ sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
+ } else {
+ sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
+ }
+ pParse.checkSchema = 1;
+ }
+ return p;
}
- pParse.checkSchema = 1;
- }
- return p;
- }
- /*
- ** Locate the in-memory structure that describes
- ** a particular index given the name of that index
- ** and the name of the database that contains the index.
- ** Return NULL if not found.
- **
- ** If zDatabase is 0, all databases are searched for the
- ** table and the first matching index is returned. (No checking
- ** for duplicate index names is done.) The search order is
- ** TEMP first, then MAIN, then any auxiliary databases added
- ** using the ATTACH command.
- */
- static Index sqlite3FindIndex( sqlite3 db, string zName, string zDb )
- {
- Index p = null;
- int i;
- int nName = sqlite3Strlen30( zName );
- /* All mutexes are required for schema access. Make sure we hold them. */
- Debug.Assert( zDb != null || sqlite3BtreeHoldsAllMutexes( db ) );
- for ( i = OMIT_TEMPDB; i < db.nDb; i++ )
- {
- int j = ( i < 2 ) ? i ^ 1 : i; /* Search TEMP before MAIN */
- Schema pSchema = db.aDb[j].pSchema;
- Debug.Assert( pSchema != null );
- if ( zDb != null && !zDb.Equals( db.aDb[j].zName, StringComparison.OrdinalIgnoreCase ) )
- continue;
- Debug.Assert( sqlite3SchemaMutexHeld( db, j, null ) );
- p = sqlite3HashFind( pSchema.idxHash, zName, nName, (Index)null );
- if ( p != null )
- break;
- }
- return p;
- }
+ /*
+ ** Locate the in-memory structure that describes
+ ** a particular index given the name of that index
+ ** and the name of the database that contains the index.
+ ** Return NULL if not found.
+ **
+ ** If zDatabase is 0, all databases are searched for the
+ ** table and the first matching index is returned. (No checking
+ ** for duplicate index names is done.) The search order is
+ ** TEMP first, then MAIN, then any auxiliary databases added
+ ** using the ATTACH command.
+ */
+ static Index sqlite3FindIndex(sqlite3 db, string zName, string zDb) {
+ Index p = null;
+ int i;
+ int nName = sqlite3Strlen30(zName);
+ /* All mutexes are required for schema access. Make sure we hold them. */
+ Debug.Assert(zDb != null || sqlite3BtreeHoldsAllMutexes(db));
+ for (i = OMIT_TEMPDB; i < db.nDb; i++) {
+ int j = (i < 2) ? i ^ 1 : i; /* Search TEMP before MAIN */
+ Schema pSchema = db.aDb[j].pSchema;
+ Debug.Assert(pSchema != null);
+ if (zDb != null && !zDb.Equals(db.aDb[j].zName, StringComparison.OrdinalIgnoreCase))
+ continue;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, j, null));
+ p = sqlite3HashFind(pSchema.idxHash, zName, nName, (Index)null);
+ if (p != null)
+ break;
+ }
+ return p;
+ }
- /*
- ** Reclaim the memory used by an index
- */
- static void freeIndex( sqlite3 db, ref Index p )
- {
+ /*
+ ** Reclaim the memory used by an index
+ */
+ static void freeIndex(sqlite3 db, ref Index p) {
#if !SQLITE_OMIT_ANALYZE
- sqlite3DeleteIndexSamples( db, p );
+ sqlite3DeleteIndexSamples(db, p);
#endif
- sqlite3DbFree( db, ref p.zColAff );
- sqlite3DbFree( db, ref p );
- }
-
- /*
- ** For the index called zIdxName which is found in the database iDb,
- ** unlike that index from its Table then remove the index from
- ** the index hash table and free all memory structures associated
- ** with the index.
- */
- static void sqlite3UnlinkAndDeleteIndex( sqlite3 db, int iDb, string zIdxName )
- {
- Index pIndex;
- int len;
- Hash pHash;
-
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- pHash = db.aDb[iDb].pSchema.idxHash;
-
- len = sqlite3Strlen30( zIdxName );
- pIndex = sqlite3HashInsert( ref pHash, zIdxName, len, (Index)null );
- if ( ALWAYS(pIndex) )
- {
- if ( pIndex.pTable.pIndex == pIndex )
- {
- pIndex.pTable.pIndex = pIndex.pNext;
+ sqlite3DbFree(db, ref p.zColAff);
+ sqlite3DbFree(db, ref p);
}
- else
- {
- Index p;
- /* Justification of ALWAYS(); The index must be on the list of
- ** indices. */
- p = pIndex.pTable.pIndex;
- while ( ALWAYS( p != null ) && p.pNext != pIndex )
- {
- p = p.pNext;
- }
- if ( ALWAYS( p != null && p.pNext == pIndex ) )
- {
- p.pNext = pIndex.pNext;
- }
- }
- freeIndex( db, ref pIndex );
- }
- db.flags |= SQLITE_InternChanges;
- }
- /*
- ** Erase all schema information from the in-memory hash tables of
- ** a single database. This routine is called to reclaim memory
- ** before the database closes. It is also called during a rollback
- ** if there were schema changes during the transaction or if a
- ** schema-cookie mismatch occurs.
- **
- ** If iDb<0 then reset the internal schema tables for all database
- ** files. If iDb>=0 then reset the internal schema for only the
- ** single file indicated.
- */
- static void sqlite3ResetInternalSchema( sqlite3 db, int iDb )
- {
- int i, j;
- Debug.Assert( iDb < db.nDb );
-
- if ( iDb >= 0 )
- {
- /* Case 1: Reset the single schema identified by iDb */
- Db pDb = db.aDb[iDb];
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- Debug.Assert( pDb.pSchema != null);
- sqlite3SchemaClear( pDb.pSchema );
-
- /* If any database other than TEMP is reset, then also reset TEMP
- ** since TEMP might be holding triggers that reference tables in the
- ** other database.
+ /*
+ ** For the index called zIdxName which is found in the database iDb,
+ ** unlike that index from its Table then remove the index from
+ ** the index hash table and free all memory structures associated
+ ** with the index.
*/
- if ( iDb != 1 )
- {
- pDb = db.aDb[1];
- Debug.Assert( pDb.pSchema != null );
- sqlite3SchemaClear( pDb.pSchema );
- }
- return;
- }
- /* Case 2 (from here to the end): Reset all schemas for all attached
- ** databases. */
- Debug.Assert( iDb < 0 );
- sqlite3BtreeEnterAll( db );
- for ( i = 0; i < db.nDb; i++ )
- {
- Db pDb = db.aDb[i];
- if ( pDb.pSchema != null )
- {
- sqlite3SchemaClear( pDb.pSchema );
- }
- }
- db.flags &= ~SQLITE_InternChanges;
- sqlite3VtabUnlockList( db );
- sqlite3BtreeLeaveAll( db );
- /* If one or more of the auxiliary database files has been closed,
- ** then remove them from the auxiliary database list. We take the
- ** opportunity to do this here since we have just deleted all of the
- ** schema hash tables and therefore do not have to make any changes
- ** to any of those tables.
- */
- for ( i = j = 2; i < db.nDb; i++ )
- {
- Db pDb = db.aDb[i];
- if ( pDb.pBt == null )
- {
- sqlite3DbFree( db, ref pDb.zName );
- continue;
+ static void sqlite3UnlinkAndDeleteIndex(sqlite3 db, int iDb, string zIdxName) {
+ Index pIndex;
+ int len;
+ Hash pHash;
+
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ pHash = db.aDb[iDb].pSchema.idxHash;
+
+ len = sqlite3Strlen30(zIdxName);
+ pIndex = sqlite3HashInsert(ref pHash, zIdxName, len, (Index)null);
+ if (ALWAYS(pIndex)) {
+ if (pIndex.pTable.pIndex == pIndex) {
+ pIndex.pTable.pIndex = pIndex.pNext;
+ } else {
+ Index p;
+ /* Justification of ALWAYS(); The index must be on the list of
+ ** indices. */
+ p = pIndex.pTable.pIndex;
+ while (ALWAYS(p != null) && p.pNext != pIndex) {
+ p = p.pNext;
+ }
+ if (ALWAYS(p != null && p.pNext == pIndex)) {
+ p.pNext = pIndex.pNext;
+ }
+ }
+ freeIndex(db, ref pIndex);
+ }
+ db.flags |= SQLITE_InternChanges;
}
- if ( j < i )
- {
- db.aDb[j] = db.aDb[i];
+
+ /*
+ ** Erase all schema information from the in-memory hash tables of
+ ** a single database. This routine is called to reclaim memory
+ ** before the database closes. It is also called during a rollback
+ ** if there were schema changes during the transaction or if a
+ ** schema-cookie mismatch occurs.
+ **
+ ** If iDb<0 then reset the internal schema tables for all database
+ ** files. If iDb>=0 then reset the internal schema for only the
+ ** single file indicated.
+ */
+ static void sqlite3ResetInternalSchema(sqlite3 db, int iDb) {
+ int i, j;
+ Debug.Assert(iDb < db.nDb);
+
+ if (iDb >= 0) {
+ /* Case 1: Reset the single schema identified by iDb */
+ Db pDb = db.aDb[iDb];
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ Debug.Assert(pDb.pSchema != null);
+ sqlite3SchemaClear(pDb.pSchema);
+
+ /* If any database other than TEMP is reset, then also reset TEMP
+ ** since TEMP might be holding triggers that reference tables in the
+ ** other database.
+ */
+ if (iDb != 1) {
+ pDb = db.aDb[1];
+ Debug.Assert(pDb.pSchema != null);
+ sqlite3SchemaClear(pDb.pSchema);
+ }
+ return;
+ }
+ /* Case 2 (from here to the end): Reset all schemas for all attached
+ ** databases. */
+ Debug.Assert(iDb < 0);
+ sqlite3BtreeEnterAll(db);
+ for (i = 0; i < db.nDb; i++) {
+ Db pDb = db.aDb[i];
+ if (pDb.pSchema != null) {
+ sqlite3SchemaClear(pDb.pSchema);
+ }
+ }
+ db.flags &= ~SQLITE_InternChanges;
+ sqlite3VtabUnlockList(db);
+ sqlite3BtreeLeaveAll(db);
+ /* If one or more of the auxiliary database files has been closed,
+ ** then remove them from the auxiliary database list. We take the
+ ** opportunity to do this here since we have just deleted all of the
+ ** schema hash tables and therefore do not have to make any changes
+ ** to any of those tables.
+ */
+ for (i = j = 2; i < db.nDb; i++) {
+ Db pDb = db.aDb[i];
+ if (pDb.pBt == null) {
+ sqlite3DbFree(db, ref pDb.zName);
+ continue;
+ }
+ if (j < i) {
+ db.aDb[j] = db.aDb[i];
+ }
+ j++;
+ }
+ if (db.nDb != j)
+ db.aDb[j] = new Db();//memset(db.aDb[j], 0, (db.nDb-j)*sizeof(db.aDb[j]));
+ db.nDb = j;
+ if (db.nDb <= 2 && db.aDb != db.aDbStatic) {
+ Array.Copy(db.aDb, db.aDbStatic, 2);// memcpy(db.aDbStatic, db.aDb, 2*sizeof(db.aDb[0]));
+ //sqlite3DbFree( db, ref db.aDb );
+ //db.aDb = db.aDbStatic;
+ }
}
- j++;
- }
- if ( db.nDb != j )
- db.aDb[j] = new Db();//memset(db.aDb[j], 0, (db.nDb-j)*sizeof(db.aDb[j]));
- db.nDb = j;
- if ( db.nDb <= 2 && db.aDb != db.aDbStatic )
- {
- Array.Copy( db.aDb, db.aDbStatic, 2 );// memcpy(db.aDbStatic, db.aDb, 2*sizeof(db.aDb[0]));
- //sqlite3DbFree( db, ref db.aDb );
- //db.aDb = db.aDbStatic;
- }
- }
- /*
- ** This routine is called when a commit occurs.
- */
- static void sqlite3CommitInternalChanges( sqlite3 db )
- {
- db.flags &= ~SQLITE_InternChanges;
- }
+ /*
+ ** This routine is called when a commit occurs.
+ */
+ static void sqlite3CommitInternalChanges(sqlite3 db) {
+ db.flags &= ~SQLITE_InternChanges;
+ }
- /*
- ** Delete memory allocated for the column names of a table or view (the
- ** Table.aCol[] array).
- */
- static void sqliteDeleteColumnNames( sqlite3 db, Table pTable )
- {
- int i;
- Column pCol;
- Debug.Assert( pTable != null );
- for ( i = 0; i < pTable.nCol; i++ )
- {
- pCol = pTable.aCol[i];
- if ( pCol != null )
- {
- sqlite3DbFree( db, ref pCol.zName );
- sqlite3ExprDelete( db, ref pCol.pDflt );
- sqlite3DbFree( db, ref pCol.zDflt );
- sqlite3DbFree( db, ref pCol.zType );
- sqlite3DbFree( db, ref pCol.zColl );
+ /*
+ ** Delete memory allocated for the column names of a table or view (the
+ ** Table.aCol[] array).
+ */
+ static void sqliteDeleteColumnNames(sqlite3 db, Table pTable) {
+ int i;
+ Column pCol;
+ Debug.Assert(pTable != null);
+ for (i = 0; i < pTable.nCol; i++) {
+ pCol = pTable.aCol[i];
+ if (pCol != null) {
+ sqlite3DbFree(db, ref pCol.zName);
+ sqlite3ExprDelete(db, ref pCol.pDflt);
+ sqlite3DbFree(db, ref pCol.zDflt);
+ sqlite3DbFree(db, ref pCol.zType);
+ sqlite3DbFree(db, ref pCol.zColl);
+ }
+ }
}
- }
- }
- /*
- ** Remove the memory data structures associated with the given
- ** Table. No changes are made to disk by this routine.
- **
- ** This routine just deletes the data structure. It does not unlink
- ** the table data structure from the hash table. But it does destroy
- ** memory structures of the indices and foreign keys associated with
- ** the table.
- */
- static void sqlite3DeleteTable( sqlite3 db, ref Table pTable )
- {
- Index pIndex;
- Index pNext;
-
- Debug.Assert( null == pTable || pTable.nRef > 0 );
-
- /* Do not delete the table until the reference count reaches zero. */
- if ( null == pTable )
- return;
- if ( (// ( !db || db->pnBytesFreed == 0 ) &&
- ( --pTable.nRef ) > 0 ) )
- return;
-
- /* Delete all indices associated with this table. */
- for ( pIndex = pTable.pIndex; pIndex != null; pIndex = pNext )
- {
- pNext = pIndex.pNext;
- Debug.Assert( pIndex.pSchema == pTable.pSchema );
- //if( null==db || db.pnBytesFreed==0 ){
- string zName = pIndex.zName;
- //
+ /*
+ ** Remove the memory data structures associated with the given
+ ** Table. No changes are made to disk by this routine.
+ **
+ ** This routine just deletes the data structure. It does not unlink
+ ** the table data structure from the hash table. But it does destroy
+ ** memory structures of the indices and foreign keys associated with
+ ** the table.
+ */
+ static void sqlite3DeleteTable(sqlite3 db, ref Table pTable) {
+ Index pIndex;
+ Index pNext;
+
+ Debug.Assert(null == pTable || pTable.nRef > 0);
+
+ /* Do not delete the table until the reference count reaches zero. */
+ if (null == pTable)
+ return;
+ if ((// ( !db || db->pnBytesFreed == 0 ) &&
+ (--pTable.nRef) > 0))
+ return;
+
+ /* Delete all indices associated with this table. */
+ for (pIndex = pTable.pIndex; pIndex != null; pIndex = pNext) {
+ pNext = pIndex.pNext;
+ Debug.Assert(pIndex.pSchema == pTable.pSchema);
+ //if( null==db || db.pnBytesFreed==0 ){
+ string zName = pIndex.zName;
+ //
#if !NDEBUG || SQLITE_COVERAGE_TEST
- // TESTONLY ( Index pOld = ) sqlite3HashInsert(
- //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
- // );
- Index pOld = sqlite3HashInsert(
- ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30( zName ), (Index)null
- );
- Debug.Assert( db == null || sqlite3SchemaMutexHeld( db, 0, pIndex.pSchema ) );
- Debug.Assert( pOld == pIndex || pOld == null );
+ // TESTONLY ( Index pOld = ) sqlite3HashInsert(
+ //ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
+ // );
+ Index pOld = sqlite3HashInsert(
+ ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), (Index)null
+ );
+ Debug.Assert(db == null || sqlite3SchemaMutexHeld(db, 0, pIndex.pSchema));
+ Debug.Assert(pOld == pIndex || pOld == null);
#else
// TESTONLY ( Index pOld = ) sqlite3HashInsert(
//ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName), 0
@@ -652,280 +601,257 @@ static void sqlite3DeleteTable( sqlite3 db, ref Table pTable )
ref pIndex.pSchema.idxHash, zName, sqlite3Strlen30(zName),(Index)null
);
#endif
- //}
- freeIndex( db, ref pIndex );
- }
+ //}
+ freeIndex(db, ref pIndex);
+ }
- /* Delete any foreign keys attached to this table. */
- sqlite3FkDelete( db, pTable );
+ /* Delete any foreign keys attached to this table. */
+ sqlite3FkDelete(db, pTable);
- /* Delete the Table structure itself.
-*/
- sqliteDeleteColumnNames( db, pTable );
- sqlite3DbFree( db, ref pTable.zName );
- sqlite3DbFree( db, ref pTable.zColAff );
- sqlite3SelectDelete( db, ref pTable.pSelect );
+ /* Delete the Table structure itself.
+ */
+ sqliteDeleteColumnNames(db, pTable);
+ sqlite3DbFree(db, ref pTable.zName);
+ sqlite3DbFree(db, ref pTable.zColAff);
+ sqlite3SelectDelete(db, ref pTable.pSelect);
#if !SQLITE_OMIT_CHECK
- sqlite3ExprDelete( db, ref pTable.pCheck );
+ sqlite3ExprDelete(db, ref pTable.pCheck);
#endif
#if !SQLITE_OMIT_VIRTUALTABLE
- sqlite3VtabClear(db, pTable);
+ sqlite3VtabClear(db, pTable);
#endif
- pTable = null;// sqlite3DbFree( db, ref pTable );
- }
-
- /*
- ** Unlink the given table from the hash tables and the delete the
- ** table structure with all its indices and foreign keys.
- */
- static void sqlite3UnlinkAndDeleteTable( sqlite3 db, int iDb, string zTabName )
- {
- Table p;
- Db pDb;
-
- Debug.Assert( db != null );
- Debug.Assert( iDb >= 0 && iDb < db.nDb );
- Debug.Assert( zTabName != null );
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- testcase( zTabName.Length == 0 ); /* Zero-length table names are allowed */
- pDb = db.aDb[iDb];
- p = sqlite3HashInsert( ref pDb.pSchema.tblHash, zTabName,
- sqlite3Strlen30( zTabName ), (Table)null );
- sqlite3DeleteTable( db, ref p );
- db.flags |= SQLITE_InternChanges;
- }
+ pTable = null;// sqlite3DbFree( db, ref pTable );
+ }
- /*
- ** Given a token, return a string that consists of the text of that
- ** token. Space to hold the returned string
- ** is obtained from sqliteMalloc() and must be freed by the calling
- ** function.
- **
- ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
- ** surround the body of the token are removed.
- **
- ** Tokens are often just pointers into the original SQL text and so
- ** are not \000 terminated and are not persistent. The returned string
- ** is \000 terminated and is persistent.
- */
- static string sqlite3NameFromToken( sqlite3 db, Token pName )
- {
- string zName;
- if ( pName != null && pName.z != null )
- {
- zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(db, (char)pName.z, pName.n);
- sqlite3Dequote( ref zName );
- }
- else
- {
- return null;
- }
- return zName;
- }
+ /*
+ ** Unlink the given table from the hash tables and the delete the
+ ** table structure with all its indices and foreign keys.
+ */
+ static void sqlite3UnlinkAndDeleteTable(sqlite3 db, int iDb, string zTabName) {
+ Table p;
+ Db pDb;
+
+ Debug.Assert(db != null);
+ Debug.Assert(iDb >= 0 && iDb < db.nDb);
+ Debug.Assert(zTabName != null);
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ testcase(zTabName.Length == 0); /* Zero-length table names are allowed */
+ pDb = db.aDb[iDb];
+ p = sqlite3HashInsert(ref pDb.pSchema.tblHash, zTabName,
+ sqlite3Strlen30(zTabName), (Table)null);
+ sqlite3DeleteTable(db, ref p);
+ db.flags |= SQLITE_InternChanges;
+ }
- /*
- ** Open the sqlite_master table stored in database number iDb for
- ** writing. The table is opened using cursor 0.
- */
- static void sqlite3OpenMasterTable( Parse p, int iDb )
- {
- Vdbe v = sqlite3GetVdbe( p );
- sqlite3TableLock( p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE( iDb ) );
- sqlite3VdbeAddOp3( v, OP_OpenWrite, 0, MASTER_ROOT, iDb );
- sqlite3VdbeChangeP4( v, -1, (int)5, P4_INT32 ); /* 5 column table */
- if ( p.nTab == 0 )
- {
- p.nTab = 1;
- }
- }
+ /*
+ ** Given a token, return a string that consists of the text of that
+ ** token. Space to hold the returned string
+ ** is obtained from sqliteMalloc() and must be freed by the calling
+ ** function.
+ **
+ ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
+ ** surround the body of the token are removed.
+ **
+ ** Tokens are often just pointers into the original SQL text and so
+ ** are not \000 terminated and are not persistent. The returned string
+ ** is \000 terminated and is persistent.
+ */
+ static string sqlite3NameFromToken(sqlite3 db, Token pName) {
+ string zName;
+ if (pName != null && pName.z != null) {
+ zName = pName.z.Substring(0, pName.n);//sqlite3DbStrNDup(db, (char)pName.z, pName.n);
+ sqlite3Dequote(ref zName);
+ } else {
+ return null;
+ }
+ return zName;
+ }
- /*
- ** Parameter zName points to a nul-terminated buffer containing the name
- ** of a database ("main", "temp" or the name of an attached db). This
- ** function returns the index of the named database in db->aDb[], or
- ** -1 if the named db cannot be found.
- */
- static int sqlite3FindDbName( sqlite3 db, string zName )
- {
- int i = -1; /* Database number */
- if ( zName != null )
- {
- Db pDb;
- int n = sqlite3Strlen30( zName );
- for ( i = ( db.nDb - 1 ); i >= 0; i-- )
- {
- pDb = db.aDb[i];
- if ( ( OMIT_TEMPDB == 0 || i != 1 ) && n == sqlite3Strlen30( pDb.zName ) &&
- pDb.zName.Equals( zName, StringComparison.OrdinalIgnoreCase ) )
- {
- break;
- }
+ /*
+ ** Open the sqlite_master table stored in database number iDb for
+ ** writing. The table is opened using cursor 0.
+ */
+ static void sqlite3OpenMasterTable(Parse p, int iDb) {
+ Vdbe v = sqlite3GetVdbe(p);
+ sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
+ sqlite3VdbeAddOp3(v, OP_OpenWrite, 0, MASTER_ROOT, iDb);
+ sqlite3VdbeChangeP4(v, -1, (int)5, P4_INT32); /* 5 column table */
+ if (p.nTab == 0) {
+ p.nTab = 1;
+ }
}
- }
- return i;
- }
- /*
- ** The token *pName contains the name of a database (either "main" or
- ** "temp" or the name of an attached db). This routine returns the
- ** index of the named database in db->aDb[], or -1 if the named db
- ** does not exist.
- */
- static int sqlite3FindDb( sqlite3 db, Token pName )
- {
- int i; /* Database number */
- string zName; /* Name we are searching for */
- zName = sqlite3NameFromToken( db, pName );
- i = sqlite3FindDbName( db, zName );
- sqlite3DbFree( db, ref zName );
- return i;
- }
+ /*
+ ** Parameter zName points to a nul-terminated buffer containing the name
+ ** of a database ("main", "temp" or the name of an attached db). This
+ ** function returns the index of the named database in db->aDb[], or
+ ** -1 if the named db cannot be found.
+ */
+ static int sqlite3FindDbName(sqlite3 db, string zName) {
+ int i = -1; /* Database number */
+ if (zName != null) {
+ Db pDb;
+ int n = sqlite3Strlen30(zName);
+ for (i = (db.nDb - 1); i >= 0; i--) {
+ pDb = db.aDb[i];
+ if ((OMIT_TEMPDB == 0 || i != 1) && n == sqlite3Strlen30(pDb.zName) &&
+ pDb.zName.Equals(zName, StringComparison.OrdinalIgnoreCase)) {
+ break;
+ }
+ }
+ }
+ return i;
+ }
- /* The table or view or trigger name is passed to this routine via tokens
- ** pName1 and pName2. If the table name was fully qualified, for example:
- **
- ** CREATE TABLE xxx.yyy (...);
- **
- ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
- ** the table name is not fully qualified, i.e.:
- **
- ** CREATE TABLE yyy(...);
- **
- ** Then pName1 is set to "yyy" and pName2 is "".
- **
- ** This routine sets the ppUnqual pointer to point at the token (pName1 or
- ** pName2) that stores the unqualified table name. The index of the
- ** database "xxx" is returned.
- */
- static int sqlite3TwoPartName(
- Parse pParse, /* Parsing and code generating context */
- Token pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
- Token pName2, /* The "yyy" in the name "xxx.yyy" */
- ref Token pUnqual /* Write the unqualified object name here */
- )
- {
- int iDb; /* Database holding the object */
- sqlite3 db = pParse.db;
-
- if ( ALWAYS( pName2 != null ) && pName2.n > 0 )
- {
- if ( db.init.busy != 0 )
- {
- sqlite3ErrorMsg( pParse, "corrupt database" );
- pParse.nErr++;
- return -1;
+ /*
+ ** The token *pName contains the name of a database (either "main" or
+ ** "temp" or the name of an attached db). This routine returns the
+ ** index of the named database in db->aDb[], or -1 if the named db
+ ** does not exist.
+ */
+ static int sqlite3FindDb(sqlite3 db, Token pName) {
+ int i; /* Database number */
+ string zName; /* Name we are searching for */
+ zName = sqlite3NameFromToken(db, pName);
+ i = sqlite3FindDbName(db, zName);
+ sqlite3DbFree(db, ref zName);
+ return i;
}
- pUnqual = pName2;
- iDb = sqlite3FindDb( db, pName1 );
- if ( iDb < 0 )
- {
- sqlite3ErrorMsg( pParse, "unknown database %T", pName1 );
- pParse.nErr++;
- return -1;
+
+ /* The table or view or trigger name is passed to this routine via tokens
+ ** pName1 and pName2. If the table name was fully qualified, for example:
+ **
+ ** CREATE TABLE xxx.yyy (...);
+ **
+ ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
+ ** the table name is not fully qualified, i.e.:
+ **
+ ** CREATE TABLE yyy(...);
+ **
+ ** Then pName1 is set to "yyy" and pName2 is "".
+ **
+ ** This routine sets the ppUnqual pointer to point at the token (pName1 or
+ ** pName2) that stores the unqualified table name. The index of the
+ ** database "xxx" is returned.
+ */
+ static int sqlite3TwoPartName(
+ Parse pParse, /* Parsing and code generating context */
+ Token pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
+ Token pName2, /* The "yyy" in the name "xxx.yyy" */
+ ref Token pUnqual /* Write the unqualified object name here */
+ ) {
+ int iDb; /* Database holding the object */
+ sqlite3 db = pParse.db;
+
+ if (ALWAYS(pName2 != null) && pName2.n > 0) {
+ if (db.init.busy != 0) {
+ sqlite3ErrorMsg(pParse, "corrupt database");
+ pParse.nErr++;
+ return -1;
+ }
+ pUnqual = pName2;
+ iDb = sqlite3FindDb(db, pName1);
+ if (iDb < 0) {
+ sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
+ pParse.nErr++;
+ return -1;
+ }
+ } else {
+ Debug.Assert(db.init.iDb == 0 || db.init.busy != 0);
+ iDb = db.init.iDb;
+ pUnqual = pName1;
+ }
+ return iDb;
}
- }
- else
- {
- Debug.Assert( db.init.iDb == 0 || db.init.busy != 0 );
- iDb = db.init.iDb;
- pUnqual = pName1;
- }
- return iDb;
- }
- /*
- ** This routine is used to check if the UTF-8 string zName is a legal
- ** unqualified name for a new schema object (vtable, index, view or
- ** trigger). All names are legal except those that begin with the string
- ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
- ** is reserved for internal use.
- */
- static int sqlite3CheckObjectName( Parse pParse, string zName )
- {
- if ( 0 == pParse.db.init.busy && pParse.nested == 0
- && ( pParse.db.flags & SQLITE_WriteSchema ) == 0
- && zName.StartsWith( "sqlite_", System.StringComparison.OrdinalIgnoreCase ) )
- {
- sqlite3ErrorMsg( pParse, "object name reserved for internal use: %s", zName );
- return SQLITE_ERROR;
- }
- return SQLITE_OK;
- }
+ /*
+ ** This routine is used to check if the UTF-8 string zName is a legal
+ ** unqualified name for a new schema object (vtable, index, view or
+ ** trigger). All names are legal except those that begin with the string
+ ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
+ ** is reserved for internal use.
+ */
+ static int sqlite3CheckObjectName(Parse pParse, string zName) {
+ if (0 == pParse.db.init.busy && pParse.nested == 0
+ && (pParse.db.flags & SQLITE_WriteSchema) == 0
+ && zName.StartsWith("sqlite_", System.StringComparison.OrdinalIgnoreCase)) {
+ sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
+ return SQLITE_ERROR;
+ }
+ return SQLITE_OK;
+ }
- /*
- ** Begin constructing a new table representation in memory. This is
- ** the first of several action routines that get called in response
- ** to a CREATE TABLE statement. In particular, this routine is called
- ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
- ** flag is true if the table should be stored in the auxiliary database
- ** file instead of in the main database file. This is normally the case
- ** when the "TEMP" or "TEMPORARY" keyword occurs in between
- ** CREATE and TABLE.
- **
- ** The new table record is initialized and put in pParse.pNewTable.
- ** As more of the CREATE TABLE statement is parsed, additional action
- ** routines will be called to add more information to this record.
- ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
- ** is called to complete the construction of the new table record.
- */
- static void sqlite3StartTable(
- Parse pParse, /* Parser context */
- Token pName1, /* First part of the name of the table or view */
- Token pName2, /* Second part of the name of the table or view */
- int isTemp, /* True if this is a TEMP table */
- int isView, /* True if this is a VIEW */
- int isVirtual, /* True if this is a VIRTUAL table */
- int noErr /* Do nothing if table already exists */
- )
- {
- Table pTable;
- string zName = null; /* The name of the new table */
- sqlite3 db = pParse.db;
- Vdbe v;
- int iDb; /* Database number to create the table in */
- Token pName = new Token(); /* Unqualified name of the table to create */
-
- /* The table or view name to create is passed to this routine via tokens
- ** pName1 and pName2. If the table name was fully qualified, for example:
- **
- ** CREATE TABLE xxx.yyy (...);
- **
- ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
- ** the table name is not fully qualified, i.e.:
- **
- ** CREATE TABLE yyy(...);
- **
- ** Then pName1 is set to "yyy" and pName2 is "".
- **
- ** The call below sets the pName pointer to point at the token (pName1 or
- ** pName2) that stores the unqualified table name. The variable iDb is
- ** set to the index of the database that the table or view is to be
- ** created in.
- */
- iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
- if ( iDb < 0 )
- return;
- if ( 0 == OMIT_TEMPDB && isTemp != 0 && pName2.n > 0 && iDb != 1 )
- {
- /* If creating a temp table, the name may not be qualified. Unless
- ** the database name is "temp" anyway. */
-
- sqlite3ErrorMsg( pParse, "temporary table name must be unqualified" );
- return;
- }
- if ( OMIT_TEMPDB == 0 && isTemp != 0 )
- iDb = 1;
-
- pParse.sNameToken = pName;
- zName = sqlite3NameFromToken( db, pName );
- if ( zName == null )
- return;
- if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
- {
- goto begin_table_error;
- }
- if ( db.init.iDb == 1 )
- isTemp = 1;
+ /*
+ ** Begin constructing a new table representation in memory. This is
+ ** the first of several action routines that get called in response
+ ** to a CREATE TABLE statement. In particular, this routine is called
+ ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
+ ** flag is true if the table should be stored in the auxiliary database
+ ** file instead of in the main database file. This is normally the case
+ ** when the "TEMP" or "TEMPORARY" keyword occurs in between
+ ** CREATE and TABLE.
+ **
+ ** The new table record is initialized and put in pParse.pNewTable.
+ ** As more of the CREATE TABLE statement is parsed, additional action
+ ** routines will be called to add more information to this record.
+ ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
+ ** is called to complete the construction of the new table record.
+ */
+ static void sqlite3StartTable(
+ Parse pParse, /* Parser context */
+ Token pName1, /* First part of the name of the table or view */
+ Token pName2, /* Second part of the name of the table or view */
+ int isTemp, /* True if this is a TEMP table */
+ int isView, /* True if this is a VIEW */
+ int isVirtual, /* True if this is a VIRTUAL table */
+ int noErr /* Do nothing if table already exists */
+ ) {
+ Table pTable;
+ string zName = null; /* The name of the new table */
+ sqlite3 db = pParse.db;
+ Vdbe v;
+ int iDb; /* Database number to create the table in */
+ Token pName = new Token(); /* Unqualified name of the table to create */
+
+ /* The table or view name to create is passed to this routine via tokens
+ ** pName1 and pName2. If the table name was fully qualified, for example:
+ **
+ ** CREATE TABLE xxx.yyy (...);
+ **
+ ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
+ ** the table name is not fully qualified, i.e.:
+ **
+ ** CREATE TABLE yyy(...);
+ **
+ ** Then pName1 is set to "yyy" and pName2 is "".
+ **
+ ** The call below sets the pName pointer to point at the token (pName1 or
+ ** pName2) that stores the unqualified table name. The variable iDb is
+ ** set to the index of the database that the table or view is to be
+ ** created in.
+ */
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, ref pName);
+ if (iDb < 0)
+ return;
+ if (0 == OMIT_TEMPDB && isTemp != 0 && pName2.n > 0 && iDb != 1) {
+ /* If creating a temp table, the name may not be qualified. Unless
+ ** the database name is "temp" anyway. */
+
+ sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
+ return;
+ }
+ if (OMIT_TEMPDB == 0 && isTemp != 0)
+ iDb = 1;
+
+ pParse.sNameToken = pName;
+ zName = sqlite3NameFromToken(db, pName);
+ if (zName == null)
+ return;
+ if (SQLITE_OK != sqlite3CheckObjectName(pParse, zName)) {
+ goto begin_table_error;
+ }
+ if (db.init.iDb == 1)
+ isTemp = 1;
#if !SQLITE_OMIT_AUTHORIZATION
Debug.Assert( (isTemp & 1)==isTemp );
{
@@ -953,1102 +879,1001 @@ static void sqlite3StartTable(
}
#endif
- /* Make sure the new table name does not collide with an existing
-** index or table name in the same database. Issue an error message if
-** it does. The exception is if the statement being parsed was passed
-** to an sqlite3_declare_vtab() call. In that case only the column names
-** and types will be used, so there is no need to test for namespace
-** collisions.
-*/
- if ( !IN_DECLARE_VTAB( pParse ) )
- {
- String zDb = db.aDb[iDb].zName;
- if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
- {
- goto begin_table_error;
- }
- pTable = sqlite3FindTable( db, zName, zDb );
- if ( pTable != null )
- {
- if ( noErr == 0 )
- {
- sqlite3ErrorMsg( pParse, "table %T already exists", pName );
- }
- else
- {
- Debug.Assert( 0 == db.init.busy );
- sqlite3CodeVerifySchema( pParse, iDb );
- }
- goto begin_table_error;
- }
- if ( sqlite3FindIndex( db, zName, zDb ) != null )
- {
- sqlite3ErrorMsg( pParse, "there is already an index named %s", zName );
- goto begin_table_error;
- }
- }
-
- pTable = new Table();// sqlite3DbMallocZero(db, Table).Length;
- //if ( pTable == null )
- //{
- // db.mallocFailed = 1;
- // pParse.rc = SQLITE_NOMEM;
- // pParse.nErr++;
- // goto begin_table_error;
- //}
- pTable.zName = zName;
- pTable.iPKey = -1;
- pTable.pSchema = db.aDb[iDb].pSchema;
- pTable.nRef = 1;
- pTable.nRowEst = 1000000;
- Debug.Assert( pParse.pNewTable == null );
- pParse.pNewTable = pTable;
-
- /* If this is the magic sqlite_sequence table used by autoincrement,
- ** then record a pointer to this table in the main database structure
- ** so that INSERT can find the table easily.
+ /* Make sure the new table name does not collide with an existing
+ ** index or table name in the same database. Issue an error message if
+ ** it does. The exception is if the statement being parsed was passed
+ ** to an sqlite3_declare_vtab() call. In that case only the column names
+ ** and types will be used, so there is no need to test for namespace
+ ** collisions.
*/
+ if (!IN_DECLARE_VTAB(pParse)) {
+ String zDb = db.aDb[iDb].zName;
+ if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
+ goto begin_table_error;
+ }
+ pTable = sqlite3FindTable(db, zName, zDb);
+ if (pTable != null) {
+ if (noErr == 0) {
+ sqlite3ErrorMsg(pParse, "table %T already exists", pName);
+ } else {
+ Debug.Assert(0 == db.init.busy);
+ sqlite3CodeVerifySchema(pParse, iDb);
+ }
+ goto begin_table_error;
+ }
+ if (sqlite3FindIndex(db, zName, zDb) != null) {
+ sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
+ goto begin_table_error;
+ }
+ }
+
+ pTable = new Table();// sqlite3DbMallocZero(db, Table).Length;
+ //if ( pTable == null )
+ //{
+ // db.mallocFailed = 1;
+ // pParse.rc = SQLITE_NOMEM;
+ // pParse.nErr++;
+ // goto begin_table_error;
+ //}
+ pTable.zName = zName;
+ pTable.iPKey = -1;
+ pTable.pSchema = db.aDb[iDb].pSchema;
+ pTable.nRef = 1;
+ pTable.nRowEst = 1000000;
+ Debug.Assert(pParse.pNewTable == null);
+ pParse.pNewTable = pTable;
+
+ /* If this is the magic sqlite_sequence table used by autoincrement,
+ ** then record a pointer to this table in the main database structure
+ ** so that INSERT can find the table easily.
+ */
#if !SQLITE_OMIT_AUTOINCREMENT
- if ( pParse.nested == 0 && zName == "sqlite_sequence" )
- {
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- pTable.pSchema.pSeqTab = pTable;
- }
+ if (pParse.nested == 0 && zName == "sqlite_sequence") {
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ pTable.pSchema.pSeqTab = pTable;
+ }
#endif
- /* Begin generating the code that will insert the table record into
-** the SQLITE_MASTER table. Note in particular that we must go ahead
-** and allocate the record number for the table entry now. Before any
-** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
-** indices to be created and the table record must come before the
-** indices. Hence, the record number for the table must be allocated
-** now.
-*/
- if ( 0 == db.init.busy && ( v = sqlite3GetVdbe( pParse ) ) != null )
- {
- int j1;
- int fileFormat;
- int reg1, reg2, reg3;
- sqlite3BeginWriteOperation( pParse, 0, iDb );
-
- if ( isVirtual != 0 )
- {
- sqlite3VdbeAddOp0( v, OP_VBegin );
+ /* Begin generating the code that will insert the table record into
+ ** the SQLITE_MASTER table. Note in particular that we must go ahead
+ ** and allocate the record number for the table entry now. Before any
+ ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
+ ** indices to be created and the table record must come before the
+ ** indices. Hence, the record number for the table must be allocated
+ ** now.
+ */
+ if (0 == db.init.busy && (v = sqlite3GetVdbe(pParse)) != null) {
+ int j1;
+ int fileFormat;
+ int reg1, reg2, reg3;
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+
+ if (isVirtual != 0) {
+ sqlite3VdbeAddOp0(v, OP_VBegin);
+ }
+
+ /* If the file format and encoding in the database have not been set,
+ ** set them now.
+ */
+ reg1 = pParse.regRowid = ++pParse.nMem;
+ reg2 = pParse.regRoot = ++pParse.nMem;
+ reg3 = ++pParse.nMem;
+ sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
+ sqlite3VdbeUsesBtree(v, iDb);
+ j1 = sqlite3VdbeAddOp1(v, OP_If, reg3);
+ fileFormat = (db.flags & SQLITE_LegacyFileFmt) != 0 ?
+ 1 : SQLITE_MAX_FILE_FORMAT;
+ sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
+ sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
+ sqlite3VdbeJumpHere(v, j1);
+
+ /* This just creates a place-holder record in the sqlite_master table.
+ ** The record created does not contain anything yet. It will be replaced
+ ** by the real entry in code generated at sqlite3EndTable().
+ **
+ ** The rowid for the new entry is left in register pParse->regRowid.
+ ** The root page number of the new table is left in reg pParse->regRoot.
+ ** The rowid and root page number values are needed by the code that
+ ** sqlite3EndTable will generate.
+ */
+ if (isView != 0 || isVirtual != 0) {
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
+ } else {
+ sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
+ }
+ sqlite3OpenMasterTable(pParse, iDb);
+ sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
+ sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
+ sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
+ sqlite3VdbeAddOp0(v, OP_Close);
+ }
+
+ /* Normal (non-error) return. */
+ return;
+
+ /* If an error occurs, we jump here */
+ begin_table_error:
+ sqlite3DbFree(db, ref zName);
+ return;
}
- /* If the file format and encoding in the database have not been set,
- ** set them now.
+ /*
+ ** This macro is used to compare two strings in a case-insensitive manner.
+ ** It is slightly faster than calling sqlite3StrICmp() directly, but
+ ** produces larger code.
+ **
+ ** WARNING: This macro is not compatible with the strcmp() family. It
+ ** returns true if the two strings are equal, otherwise false.
*/
- reg1 = pParse.regRowid = ++pParse.nMem;
- reg2 = pParse.regRoot = ++pParse.nMem;
- reg3 = ++pParse.nMem;
- sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT );
- sqlite3VdbeUsesBtree( v, iDb );
- j1 = sqlite3VdbeAddOp1( v, OP_If, reg3 );
- fileFormat = ( db.flags & SQLITE_LegacyFileFmt ) != 0 ?
- 1 : SQLITE_MAX_FILE_FORMAT;
- sqlite3VdbeAddOp2( v, OP_Integer, fileFormat, reg3 );
- sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3 );
- sqlite3VdbeAddOp2( v, OP_Integer, ENC( db ), reg3 );
- sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3 );
- sqlite3VdbeJumpHere( v, j1 );
-
- /* This just creates a place-holder record in the sqlite_master table.
- ** The record created does not contain anything yet. It will be replaced
- ** by the real entry in code generated at sqlite3EndTable().
+ //#define STRICMP(x, y) (\
+ //sqlite3UpperToLower[*(unsigned char )(x)]== \
+ //sqlite3UpperToLower[*(unsigned char )(y)] \
+ //&& sqlite3StrICmp((x)+1,(y)+1)==0 )
+
+ /*
+ ** Add a new column to the table currently being constructed.
**
- ** The rowid for the new entry is left in register pParse->regRowid.
- ** The root page number of the new table is left in reg pParse->regRoot.
- ** The rowid and root page number values are needed by the code that
- ** sqlite3EndTable will generate.
+ ** The parser calls this routine once for each column declaration
+ ** in a CREATE TABLE statement. sqlite3StartTable() gets called
+ ** first to get things going. Then this routine is called for each
+ ** column.
*/
- if ( isView != 0 || isVirtual != 0 )
- {
- sqlite3VdbeAddOp2( v, OP_Integer, 0, reg2 );
+ static void sqlite3AddColumn(Parse pParse, Token pName) {
+ Table p;
+ int i;
+ string z;
+ Column pCol;
+ sqlite3 db = pParse.db;
+ if ((p = pParse.pNewTable) == null)
+ return;
+#if SQLITE_MAX_COLUMN || !SQLITE_MAX_COLUMN
+ if (p.nCol + 1 > db.aLimit[SQLITE_LIMIT_COLUMN]) {
+ sqlite3ErrorMsg(pParse, "too many columns on %s", p.zName);
+ return;
+ }
+#endif
+ z = sqlite3NameFromToken(db, pName);
+ if (z == null)
+ return;
+ for (i = 0; i < p.nCol; i++) {
+ if (z.Equals(p.aCol[i].zName, StringComparison.OrdinalIgnoreCase)) {//STRICMP(z, p.aCol[i].zName) ){
+ sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
+ sqlite3DbFree(db, ref z);
+ return;
+ }
+ }
+ if ((p.nCol & 0x7) == 0) {
+ //aNew = sqlite3DbRealloc(db,p.aCol,(p.nCol+8)*sizeof(p.aCol[0]));
+ //if( aNew==0 ){
+ // sqlite3DbFree(db,ref z);
+ // return;
+ //}
+ Array.Resize(ref p.aCol, p.nCol + 8);
+ }
+ p.aCol[p.nCol] = new Column();
+ pCol = p.aCol[p.nCol];
+ //memset(pCol, 0, sizeof(p.aCol[0]));
+ pCol.zName = z;
+
+ /* If there is no type specified, columns have the default affinity
+ ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
+ ** be called next to set pCol.affinity correctly.
+ */
+ pCol.affinity = SQLITE_AFF_NONE;
+ p.nCol++;
}
- else
- {
- sqlite3VdbeAddOp2( v, OP_CreateTable, iDb, reg2 );
+
+ /*
+ ** This routine is called by the parser while in the middle of
+ ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
+ ** been seen on a column. This routine sets the notNull flag on
+ ** the column currently under construction.
+ */
+ static void sqlite3AddNotNull(Parse pParse, int onError) {
+ Table p;
+ p = pParse.pNewTable;
+ if (p == null || NEVER(p.nCol < 1))
+ return;
+ p.aCol[p.nCol - 1].notNull = (u8)onError;
}
- sqlite3OpenMasterTable( pParse, iDb );
- sqlite3VdbeAddOp2( v, OP_NewRowid, 0, reg1 );
- sqlite3VdbeAddOp2( v, OP_Null, 0, reg3 );
- sqlite3VdbeAddOp3( v, OP_Insert, 0, reg3, reg1 );
- sqlite3VdbeChangeP5( v, OPFLAG_APPEND );
- sqlite3VdbeAddOp0( v, OP_Close );
- }
-
- /* Normal (non-error) return. */
- return;
- /* If an error occurs, we jump here */
-begin_table_error:
- sqlite3DbFree( db, ref zName );
- return;
- }
+ /*
+ ** Scan the column type name zType (length nType) and return the
+ ** associated affinity type.
+ **
+ ** This routine does a case-independent search of zType for the
+ ** substrings in the following table. If one of the substrings is
+ ** found, the corresponding affinity is returned. If zType contains
+ ** more than one of the substrings, entries toward the top of
+ ** the table take priority. For example, if zType is 'BLOBINT',
+ ** SQLITE_AFF_INTEGER is returned.
+ **
+ ** Substring | Affinity
+ ** --------------------------------
+ ** 'INT' | SQLITE_AFF_INTEGER
+ ** 'CHAR' | SQLITE_AFF_TEXT
+ ** 'CLOB' | SQLITE_AFF_TEXT
+ ** 'TEXT' | SQLITE_AFF_TEXT
+ ** 'BLOB' | SQLITE_AFF_NONE
+ ** 'REAL' | SQLITE_AFF_REAL
+ ** 'FLOA' | SQLITE_AFF_REAL
+ ** 'DOUB' | SQLITE_AFF_REAL
+ **
+ ** If none of the substrings in the above table are found,
+ ** SQLITE_AFF_NUMERIC is returned.
+ */
+ static char sqlite3AffinityType(string zIn) {
+ //u32 h = 0;
+ //char aff = SQLITE_AFF_NUMERIC;
+ zIn = zIn.ToLowerInvariant();
+ if (zIn.Contains("char") || zIn.Contains("clob") || zIn.Contains("text"))
+ return SQLITE_AFF_TEXT;
+ if (zIn.Contains("blob"))
+ return SQLITE_AFF_NONE;
+ if (zIn.Contains("doub") || zIn.Contains("floa") || zIn.Contains("real"))
+ return SQLITE_AFF_REAL;
+ if (zIn.Contains("int"))
+ return SQLITE_AFF_INTEGER;
+ return SQLITE_AFF_NUMERIC;
+ // string zEnd = pType.z.Substring(pType.n);
+
+ // while( zIn!=zEnd ){
+ // h = (h<<8) + sqlite3UpperToLower[*zIn];
+ // zIn++;
+ // if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
+ // aff = SQLITE_AFF_TEXT;
+ // }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
+ // aff = SQLITE_AFF_TEXT;
+ // }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
+ // aff = SQLITE_AFF_TEXT;
+ // }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
+ // && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
+ // aff = SQLITE_AFF_NONE;
+ //#if !SQLITE_OMIT_FLOATING_POINT
+ // }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
+ // && aff==SQLITE_AFF_NUMERIC ){
+ // aff = SQLITE_AFF_REAL;
+ // }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
+ // && aff==SQLITE_AFF_NUMERIC ){
+ // aff = SQLITE_AFF_REAL;
+ // }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
+ // && aff==SQLITE_AFF_NUMERIC ){
+ // aff = SQLITE_AFF_REAL;
+ //#endif
+ // }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
+ // aff = SQLITE_AFF_INTEGER;
+ // break;
+ // }
+ // }
+
+ // return aff;
+ }
- /*
- ** This macro is used to compare two strings in a case-insensitive manner.
- ** It is slightly faster than calling sqlite3StrICmp() directly, but
- ** produces larger code.
- **
- ** WARNING: This macro is not compatible with the strcmp() family. It
- ** returns true if the two strings are equal, otherwise false.
- */
- //#define STRICMP(x, y) (\
- //sqlite3UpperToLower[*(unsigned char )(x)]== \
- //sqlite3UpperToLower[*(unsigned char )(y)] \
- //&& sqlite3StrICmp((x)+1,(y)+1)==0 )
+ /*
+ ** This routine is called by the parser while in the middle of
+ ** parsing a CREATE TABLE statement. The pFirst token is the first
+ ** token in the sequence of tokens that describe the type of the
+ ** column currently under construction. pLast is the last token
+ ** in the sequence. Use this information to construct a string
+ ** that contains the typename of the column and store that string
+ ** in zType.
+ */
+ static void sqlite3AddColumnType(Parse pParse, Token pType) {
+ Table p;
+ Column pCol;
- /*
- ** Add a new column to the table currently being constructed.
- **
- ** The parser calls this routine once for each column declaration
- ** in a CREATE TABLE statement. sqlite3StartTable() gets called
- ** first to get things going. Then this routine is called for each
- ** column.
- */
- static void sqlite3AddColumn( Parse pParse, Token pName )
- {
- Table p;
- int i;
- string z;
- Column pCol;
- sqlite3 db = pParse.db;
- if ( ( p = pParse.pNewTable ) == null )
- return;
-#if SQLITE_MAX_COLUMN || !SQLITE_MAX_COLUMN
- if ( p.nCol + 1 > db.aLimit[SQLITE_LIMIT_COLUMN] )
- {
- sqlite3ErrorMsg( pParse, "too many columns on %s", p.zName );
- return;
- }
-#endif
- z = sqlite3NameFromToken( db, pName );
- if ( z == null )
- return;
- for ( i = 0; i < p.nCol; i++ )
- {
- if ( z.Equals( p.aCol[i].zName, StringComparison.OrdinalIgnoreCase ) )
- {//STRICMP(z, p.aCol[i].zName) ){
- sqlite3ErrorMsg( pParse, "duplicate column name: %s", z );
- sqlite3DbFree( db, ref z );
- return;
+ p = pParse.pNewTable;
+ if (p == null || NEVER(p.nCol < 1))
+ return;
+ pCol = p.aCol[p.nCol - 1];
+ Debug.Assert(pCol.zType == null);
+ pCol.zType = sqlite3NameFromToken(pParse.db, pType);
+ pCol.affinity = sqlite3AffinityType(pCol.zType);
}
- }
- if ( ( p.nCol & 0x7 ) == 0 )
- {
- //aNew = sqlite3DbRealloc(db,p.aCol,(p.nCol+8)*sizeof(p.aCol[0]));
- //if( aNew==0 ){
- // sqlite3DbFree(db,ref z);
- // return;
- //}
- Array.Resize( ref p.aCol, p.nCol + 8 );
- }
- p.aCol[p.nCol] = new Column();
- pCol = p.aCol[p.nCol];
- //memset(pCol, 0, sizeof(p.aCol[0]));
- pCol.zName = z;
-
- /* If there is no type specified, columns have the default affinity
- ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
- ** be called next to set pCol.affinity correctly.
- */
- pCol.affinity = SQLITE_AFF_NONE;
- p.nCol++;
- }
-
- /*
- ** This routine is called by the parser while in the middle of
- ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
- ** been seen on a column. This routine sets the notNull flag on
- ** the column currently under construction.
- */
- static void sqlite3AddNotNull( Parse pParse, int onError )
- {
- Table p;
- p = pParse.pNewTable;
- if ( p == null || NEVER( p.nCol < 1 ) )
- return;
- p.aCol[p.nCol - 1].notNull = (u8)onError;
- }
-
- /*
- ** Scan the column type name zType (length nType) and return the
- ** associated affinity type.
- **
- ** This routine does a case-independent search of zType for the
- ** substrings in the following table. If one of the substrings is
- ** found, the corresponding affinity is returned. If zType contains
- ** more than one of the substrings, entries toward the top of
- ** the table take priority. For example, if zType is 'BLOBINT',
- ** SQLITE_AFF_INTEGER is returned.
- **
- ** Substring | Affinity
- ** --------------------------------
- ** 'INT' | SQLITE_AFF_INTEGER
- ** 'CHAR' | SQLITE_AFF_TEXT
- ** 'CLOB' | SQLITE_AFF_TEXT
- ** 'TEXT' | SQLITE_AFF_TEXT
- ** 'BLOB' | SQLITE_AFF_NONE
- ** 'REAL' | SQLITE_AFF_REAL
- ** 'FLOA' | SQLITE_AFF_REAL
- ** 'DOUB' | SQLITE_AFF_REAL
- **
- ** If none of the substrings in the above table are found,
- ** SQLITE_AFF_NUMERIC is returned.
- */
- static char sqlite3AffinityType( string zIn )
- {
- //u32 h = 0;
- //char aff = SQLITE_AFF_NUMERIC;
- zIn = zIn.ToLowerInvariant();
- if ( zIn.Contains( "char" ) || zIn.Contains( "clob" ) || zIn.Contains( "text" ) )
- return SQLITE_AFF_TEXT;
- if ( zIn.Contains( "blob" ) )
- return SQLITE_AFF_NONE;
- if ( zIn.Contains( "doub" ) || zIn.Contains( "floa" ) || zIn.Contains( "real" ) )
- return SQLITE_AFF_REAL;
- if ( zIn.Contains( "int" ) )
- return SQLITE_AFF_INTEGER;
- return SQLITE_AFF_NUMERIC;
- // string zEnd = pType.z.Substring(pType.n);
-
- // while( zIn!=zEnd ){
- // h = (h<<8) + sqlite3UpperToLower[*zIn];
- // zIn++;
- // if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
- // aff = SQLITE_AFF_TEXT;
- // }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
- // aff = SQLITE_AFF_TEXT;
- // }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
- // aff = SQLITE_AFF_TEXT;
- // }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
- // && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
- // aff = SQLITE_AFF_NONE;
- //#if !SQLITE_OMIT_FLOATING_POINT
- // }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
- // && aff==SQLITE_AFF_NUMERIC ){
- // aff = SQLITE_AFF_REAL;
- // }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
- // && aff==SQLITE_AFF_NUMERIC ){
- // aff = SQLITE_AFF_REAL;
- // }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
- // && aff==SQLITE_AFF_NUMERIC ){
- // aff = SQLITE_AFF_REAL;
- //#endif
- // }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
- // aff = SQLITE_AFF_INTEGER;
- // break;
- // }
- // }
-
- // return aff;
- }
-
- /*
- ** This routine is called by the parser while in the middle of
- ** parsing a CREATE TABLE statement. The pFirst token is the first
- ** token in the sequence of tokens that describe the type of the
- ** column currently under construction. pLast is the last token
- ** in the sequence. Use this information to construct a string
- ** that contains the typename of the column and store that string
- ** in zType.
- */
- static void sqlite3AddColumnType( Parse pParse, Token pType )
- {
- Table p;
- Column pCol;
-
- p = pParse.pNewTable;
- if ( p == null || NEVER( p.nCol < 1 ) )
- return;
- pCol = p.aCol[p.nCol - 1];
- Debug.Assert( pCol.zType == null );
- pCol.zType = sqlite3NameFromToken( pParse.db, pType );
- pCol.affinity = sqlite3AffinityType( pCol.zType );
- }
- /*
- ** The expression is the default value for the most recently added column
- ** of the table currently under construction.
- **
- ** Default value expressions must be constant. Raise an exception if this
- ** is not the case.
- **
- ** This routine is called by the parser while in the middle of
- ** parsing a CREATE TABLE statement.
- */
- static void sqlite3AddDefaultValue( Parse pParse, ExprSpan pSpan )
- {
- Table p;
- Column pCol;
- sqlite3 db = pParse.db;
- p = pParse.pNewTable;
- if ( p != null )
- {
- pCol = ( p.aCol[p.nCol - 1] );
- if ( sqlite3ExprIsConstantOrFunction( pSpan.pExpr ) == 0 )
- {
- sqlite3ErrorMsg( pParse, "default value of column [%s] is not constant",
- pCol.zName );
- }
- else
- {
- /* A copy of pExpr is used instead of the original, as pExpr contains
- ** tokens that point to volatile memory. The 'span' of the expression
- ** is required by pragma table_info.
- */
- sqlite3ExprDelete( db, ref pCol.pDflt );
- pCol.pDflt = sqlite3ExprDup( db, pSpan.pExpr, EXPRDUP_REDUCE );
- sqlite3DbFree( db, ref pCol.zDflt );
- pCol.zDflt = pSpan.zStart.Substring( 0, pSpan.zStart.Length - pSpan.zEnd.Length );
- //sqlite3DbStrNDup( db, pSpan.zStart,
- // (int)( pSpan.zEnd.Length - pSpan.zStart.Length ) );
+ /*
+ ** The expression is the default value for the most recently added column
+ ** of the table currently under construction.
+ **
+ ** Default value expressions must be constant. Raise an exception if this
+ ** is not the case.
+ **
+ ** This routine is called by the parser while in the middle of
+ ** parsing a CREATE TABLE statement.
+ */
+ static void sqlite3AddDefaultValue(Parse pParse, ExprSpan pSpan) {
+ Table p;
+ Column pCol;
+ sqlite3 db = pParse.db;
+ p = pParse.pNewTable;
+ if (p != null) {
+ pCol = (p.aCol[p.nCol - 1]);
+ if (sqlite3ExprIsConstantOrFunction(pSpan.pExpr) == 0) {
+ sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
+ pCol.zName);
+ } else {
+ /* A copy of pExpr is used instead of the original, as pExpr contains
+ ** tokens that point to volatile memory. The 'span' of the expression
+ ** is required by pragma table_info.
+ */
+ sqlite3ExprDelete(db, ref pCol.pDflt);
+ pCol.pDflt = sqlite3ExprDup(db, pSpan.pExpr, EXPRDUP_REDUCE);
+ sqlite3DbFree(db, ref pCol.zDflt);
+ pCol.zDflt = pSpan.zStart.Substring(0, pSpan.zStart.Length - pSpan.zEnd.Length);
+ //sqlite3DbStrNDup( db, pSpan.zStart,
+ // (int)( pSpan.zEnd.Length - pSpan.zStart.Length ) );
+ }
+ }
+ sqlite3ExprDelete(db, ref pSpan.pExpr);
}
- }
- sqlite3ExprDelete( db, ref pSpan.pExpr );
- }
- /*
- ** Designate the PRIMARY KEY for the table. pList is a list of names
- ** of columns that form the primary key. If pList is NULL, then the
- ** most recently added column of the table is the primary key.
- **
- ** A table can have at most one primary key. If the table already has
- ** a primary key (and this is the second primary key) then create an
- ** error.
- **
- ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
- ** then we will try to use that column as the rowid. Set the Table.iPKey
- ** field of the table under construction to be the index of the
- ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
- ** no INTEGER PRIMARY KEY.
- **
- ** If the key is not an INTEGER PRIMARY KEY, then create a unique
- ** index for the key. No index is created for INTEGER PRIMARY KEYs.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static void sqlite3AddPrimaryKey( Parse pParse, int null_2, int onError, int autoInc, int sortOrder )
- {
- sqlite3AddPrimaryKey( pParse, null, onError, autoInc, sortOrder );
- }
- static void sqlite3AddPrimaryKey(
- Parse pParse, /* Parsing context */
- ExprList pList, /* List of field names to be indexed */
- int onError, /* What to do with a uniqueness conflict */
- int autoInc, /* True if the AUTOINCREMENT keyword is present */
- int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
- )
- {
- Table pTab = pParse.pNewTable;
- string zType = null;
- int iCol = -1, i;
- if ( pTab == null || IN_DECLARE_VTAB( pParse ) )
- goto primary_key_exit;
- if ( ( pTab.tabFlags & TF_HasPrimaryKey ) != 0 )
- {
- sqlite3ErrorMsg( pParse,
- "table \"%s\" has more than one primary key", pTab.zName );
- goto primary_key_exit;
- }
- pTab.tabFlags |= TF_HasPrimaryKey;
- if ( pList == null )
- {
- iCol = pTab.nCol - 1;
- pTab.aCol[iCol].isPrimKey = 1;
- }
- else
- {
- for ( i = 0; i < pList.nExpr; i++ )
- {
- for ( iCol = 0; iCol < pTab.nCol; iCol++ )
- {
- if ( pList.a[i].zName.Equals( pTab.aCol[iCol].zName, StringComparison.OrdinalIgnoreCase ) )
- {
- break;
+ /*
+ ** Designate the PRIMARY KEY for the table. pList is a list of names
+ ** of columns that form the primary key. If pList is NULL, then the
+ ** most recently added column of the table is the primary key.
+ **
+ ** A table can have at most one primary key. If the table already has
+ ** a primary key (and this is the second primary key) then create an
+ ** error.
+ **
+ ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
+ ** then we will try to use that column as the rowid. Set the Table.iPKey
+ ** field of the table under construction to be the index of the
+ ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
+ ** no INTEGER PRIMARY KEY.
+ **
+ ** If the key is not an INTEGER PRIMARY KEY, then create a unique
+ ** index for the key. No index is created for INTEGER PRIMARY KEYs.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static void sqlite3AddPrimaryKey(Parse pParse, int null_2, int onError, int autoInc, int sortOrder) {
+ sqlite3AddPrimaryKey(pParse, null, onError, autoInc, sortOrder);
+ }
+ static void sqlite3AddPrimaryKey(
+ Parse pParse, /* Parsing context */
+ ExprList pList, /* List of field names to be indexed */
+ int onError, /* What to do with a uniqueness conflict */
+ int autoInc, /* True if the AUTOINCREMENT keyword is present */
+ int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
+ ) {
+ Table pTab = pParse.pNewTable;
+ string zType = null;
+ int iCol = -1, i;
+ if (pTab == null || IN_DECLARE_VTAB(pParse))
+ goto primary_key_exit;
+ if ((pTab.tabFlags & TF_HasPrimaryKey) != 0) {
+ sqlite3ErrorMsg(pParse,
+ "table \"%s\" has more than one primary key", pTab.zName);
+ goto primary_key_exit;
}
- }
- if ( iCol < pTab.nCol )
- {
- pTab.aCol[iCol].isPrimKey = 1;
- }
- }
- if ( pList.nExpr > 1 )
- iCol = -1;
- }
- if ( iCol >= 0 && iCol < pTab.nCol )
- {
- zType = pTab.aCol[iCol].zType;
- }
- if ( zType != null && zType.Equals( "INTEGER", StringComparison.OrdinalIgnoreCase )
- && sortOrder == SQLITE_SO_ASC )
- {
- pTab.iPKey = iCol;
- pTab.keyConf = (byte)onError;
- Debug.Assert( autoInc == 0 || autoInc == 1 );
- pTab.tabFlags |= (u8)( autoInc * TF_Autoincrement );
- }
- else if ( autoInc != 0 )
- {
+ pTab.tabFlags |= TF_HasPrimaryKey;
+ if (pList == null) {
+ iCol = pTab.nCol - 1;
+ pTab.aCol[iCol].isPrimKey = 1;
+ } else {
+ for (i = 0; i < pList.nExpr; i++) {
+ for (iCol = 0; iCol < pTab.nCol; iCol++) {
+ if (pList.a[i].zName.Equals(pTab.aCol[iCol].zName, StringComparison.OrdinalIgnoreCase)) {
+ break;
+ }
+ }
+ if (iCol < pTab.nCol) {
+ pTab.aCol[iCol].isPrimKey = 1;
+ }
+ }
+ if (pList.nExpr > 1)
+ iCol = -1;
+ }
+ if (iCol >= 0 && iCol < pTab.nCol) {
+ zType = pTab.aCol[iCol].zType;
+ }
+ if (zType != null && zType.Equals("INTEGER", StringComparison.OrdinalIgnoreCase)
+ && sortOrder == SQLITE_SO_ASC) {
+ pTab.iPKey = iCol;
+ pTab.keyConf = (byte)onError;
+ Debug.Assert(autoInc == 0 || autoInc == 1);
+ pTab.tabFlags |= (u8)(autoInc * TF_Autoincrement);
+ } else if (autoInc != 0) {
#if !SQLITE_OMIT_AUTOINCREMENT
- sqlite3ErrorMsg( pParse, "AUTOINCREMENT is only allowed on an " +
- "INTEGER PRIMARY KEY" );
+ sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an " +
+ "INTEGER PRIMARY KEY");
#endif
- }
- else
- {
- Index p;
- p = sqlite3CreateIndex( pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0 );
- if ( p != null )
- {
- p.autoIndex = 2;
- }
- pList = null;
- }
+ } else {
+ Index p;
+ p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0, 0, sortOrder, 0);
+ if (p != null) {
+ p.autoIndex = 2;
+ }
+ pList = null;
+ }
-primary_key_exit:
- sqlite3ExprListDelete( pParse.db, ref pList );
- return;
- }
+ primary_key_exit:
+ sqlite3ExprListDelete(pParse.db, ref pList);
+ return;
+ }
- /*
- ** Add a new CHECK constraint to the table currently under construction.
- */
- static void sqlite3AddCheckConstraint(
- Parse pParse, /* Parsing context */
- Expr pCheckExpr /* The check expression */
- )
- {
- sqlite3 db = pParse.db;
+ /*
+ ** Add a new CHECK constraint to the table currently under construction.
+ */
+ static void sqlite3AddCheckConstraint(
+ Parse pParse, /* Parsing context */
+ Expr pCheckExpr /* The check expression */
+ ) {
+ sqlite3 db = pParse.db;
#if !SQLITE_OMIT_CHECK
- Table pTab = pParse.pNewTable;
- if ( pTab != null && !IN_DECLARE_VTAB( pParse ) )
- {
- pTab.pCheck = sqlite3ExprAnd( db, pTab.pCheck, pCheckExpr );
- }
- else
+ Table pTab = pParse.pNewTable;
+ if (pTab != null && !IN_DECLARE_VTAB(pParse)) {
+ pTab.pCheck = sqlite3ExprAnd(db, pTab.pCheck, pCheckExpr);
+ } else
#endif
- {
- sqlite3ExprDelete( db, ref pCheckExpr );
- }
- }
- /*
- ** Set the collation function of the most recently parsed table column
- ** to the CollSeq given.
- */
- static void sqlite3AddCollateType( Parse pParse, Token pToken )
- {
- Table p;
- int i;
- string zColl; /* Dequoted name of collation sequence */
- sqlite3 db;
-
- if ( ( p = pParse.pNewTable ) == null )
- return;
- i = p.nCol - 1;
- db = pParse.db;
- zColl = sqlite3NameFromToken( db, pToken );
- if ( zColl == null )
- return;
-
- if ( sqlite3LocateCollSeq( pParse, zColl ) != null )
- {
- Index pIdx;
- p.aCol[i].zColl = zColl;
-
- /* If the column is declared as " PRIMARY KEY COLLATE ",
- ** then an index may have been created on this column before the
- ** collation type was added. Correct this if it is the case.
+ {
+ sqlite3ExprDelete(db, ref pCheckExpr);
+ }
+ }
+ /*
+ ** Set the collation function of the most recently parsed table column
+ ** to the CollSeq given.
*/
- for ( pIdx = p.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- Debug.Assert( pIdx.nColumn == 1 );
- if ( pIdx.aiColumn[0] == i )
- {
- pIdx.azColl[0] = p.aCol[i].zColl;
- }
+ static void sqlite3AddCollateType(Parse pParse, Token pToken) {
+ Table p;
+ int i;
+ string zColl; /* Dequoted name of collation sequence */
+ sqlite3 db;
+
+ if ((p = pParse.pNewTable) == null)
+ return;
+ i = p.nCol - 1;
+ db = pParse.db;
+ zColl = sqlite3NameFromToken(db, pToken);
+ if (zColl == null)
+ return;
+
+ if (sqlite3LocateCollSeq(pParse, zColl) != null) {
+ Index pIdx;
+ p.aCol[i].zColl = zColl;
+
+ /* If the column is declared as " PRIMARY KEY COLLATE ",
+ ** then an index may have been created on this column before the
+ ** collation type was added. Correct this if it is the case.
+ */
+ for (pIdx = p.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ Debug.Assert(pIdx.nColumn == 1);
+ if (pIdx.aiColumn[0] == i) {
+ pIdx.azColl[0] = p.aCol[i].zColl;
+ }
+ }
+ } else {
+ sqlite3DbFree(db, ref zColl);
+ }
}
- }
- else
- {
- sqlite3DbFree( db, ref zColl );
- }
- }
- /*
- ** This function returns the collation sequence for database native text
- ** encoding identified by the string zName, length nName.
- **
- ** If the requested collation sequence is not available, or not available
- ** in the database native encoding, the collation factory is invoked to
- ** request it. If the collation factory does not supply such a sequence,
- ** and the sequence is available in another text encoding, then that is
- ** returned instead.
- **
- ** If no versions of the requested collations sequence are available, or
- ** another error occurs, NULL is returned and an error message written into
- ** pParse.
- **
- ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
- ** invokes the collation factory if the named collation cannot be found
- ** and generates an error message.
- **
- ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
- */
- static CollSeq sqlite3LocateCollSeq( Parse pParse, string zName )
- {
- sqlite3 db = pParse.db;
- u8 enc = db.aDb[0].pSchema.enc;// ENC(db);
- u8 initbusy = db.init.busy;
- CollSeq pColl;
-
- pColl = sqlite3FindCollSeq( db, enc, zName, initbusy );
- if ( 0 == initbusy && ( pColl == null || pColl.xCmp == null ) )
- {
- pColl = sqlite3GetCollSeq( db, enc, pColl, zName );
- if ( pColl == null )
- {
- sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName );
- }
- }
+ /*
+ ** This function returns the collation sequence for database native text
+ ** encoding identified by the string zName, length nName.
+ **
+ ** If the requested collation sequence is not available, or not available
+ ** in the database native encoding, the collation factory is invoked to
+ ** request it. If the collation factory does not supply such a sequence,
+ ** and the sequence is available in another text encoding, then that is
+ ** returned instead.
+ **
+ ** If no versions of the requested collations sequence are available, or
+ ** another error occurs, NULL is returned and an error message written into
+ ** pParse.
+ **
+ ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
+ ** invokes the collation factory if the named collation cannot be found
+ ** and generates an error message.
+ **
+ ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
+ */
+ static CollSeq sqlite3LocateCollSeq(Parse pParse, string zName) {
+ sqlite3 db = pParse.db;
+ u8 enc = db.aDb[0].pSchema.enc;// ENC(db);
+ u8 initbusy = db.init.busy;
+ CollSeq pColl;
+
+ pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
+ if (0 == initbusy && (pColl == null || pColl.xCmp == null)) {
+ pColl = sqlite3GetCollSeq(db, enc, pColl, zName);
+ if (pColl == null) {
+ sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
+ }
+ }
- return pColl;
- }
+ return pColl;
+ }
- /*
- ** Generate code that will increment the schema cookie.
- **
- ** The schema cookie is used to determine when the schema for the
- ** database changes. After each schema change, the cookie value
- ** changes. When a process first reads the schema it records the
- ** cookie. Thereafter, whenever it goes to access the database,
- ** it checks the cookie to make sure the schema has not changed
- ** since it was last read.
- **
- ** This plan is not completely bullet-proof. It is possible for
- ** the schema to change multiple times and for the cookie to be
- ** set back to prior value. But schema changes are infrequent
- ** and the probability of hitting the same cookie value is only
- ** 1 chance in 2^32. So we're safe enough.
- */
- static void sqlite3ChangeCookie( Parse pParse, int iDb )
- {
- int r1 = sqlite3GetTempReg( pParse );
- sqlite3 db = pParse.db;
- Vdbe v = pParse.pVdbe;
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- sqlite3VdbeAddOp2( v, OP_Integer, db.aDb[iDb].pSchema.schema_cookie + 1, r1 );
- sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1 );
- sqlite3ReleaseTempReg( pParse, r1 );
- }
+ /*
+ ** Generate code that will increment the schema cookie.
+ **
+ ** The schema cookie is used to determine when the schema for the
+ ** database changes. After each schema change, the cookie value
+ ** changes. When a process first reads the schema it records the
+ ** cookie. Thereafter, whenever it goes to access the database,
+ ** it checks the cookie to make sure the schema has not changed
+ ** since it was last read.
+ **
+ ** This plan is not completely bullet-proof. It is possible for
+ ** the schema to change multiple times and for the cookie to be
+ ** set back to prior value. But schema changes are infrequent
+ ** and the probability of hitting the same cookie value is only
+ ** 1 chance in 2^32. So we're safe enough.
+ */
+ static void sqlite3ChangeCookie(Parse pParse, int iDb) {
+ int r1 = sqlite3GetTempReg(pParse);
+ sqlite3 db = pParse.db;
+ Vdbe v = pParse.pVdbe;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ sqlite3VdbeAddOp2(v, OP_Integer, db.aDb[iDb].pSchema.schema_cookie + 1, r1);
+ sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
+ sqlite3ReleaseTempReg(pParse, r1);
+ }
- /*
- ** Measure the number of characters needed to output the given
- ** identifier. The number returned includes any quotes used
- ** but does not include the null terminator.
- **
- ** The estimate is conservative. It might be larger that what is
- ** really needed.
- */
- static int identLength( string z )
- {
- int n;
- for ( n = 0; n < z.Length; n++ )
- {
- if ( z[n] == (byte)'"' )
- {
- n++;
+ /*
+ ** Measure the number of characters needed to output the given
+ ** identifier. The number returned includes any quotes used
+ ** but does not include the null terminator.
+ **
+ ** The estimate is conservative. It might be larger that what is
+ ** really needed.
+ */
+ static int identLength(string z) {
+ int n;
+ for (n = 0; n < z.Length; n++) {
+ if (z[n] == (byte)'"') {
+ n++;
+ }
+ }
+ return n + 2;
}
- }
- return n + 2;
- }
- /*
- ** The first parameter is a pointer to an output buffer. The second
- ** parameter is a pointer to an integer that contains the offset at
- ** which to write into the output buffer. This function copies the
- ** nul-terminated string pointed to by the third parameter, zSignedIdent,
- ** to the specified offset in the buffer and updates *pIdx to refer
- ** to the first byte after the last byte written before returning.
- **
- ** If the string zSignedIdent consists entirely of alpha-numeric
- ** characters, does not begin with a digit and is not an SQL keyword,
- ** then it is copied to the output buffer exactly as it is. Otherwise,
- ** it is quoted using double-quotes.
- */
- static void identPut( StringBuilder z, ref int pIdx, string zSignedIdent )
- {
- string zIdent = zSignedIdent;
- int i;
- int j;
- bool needQuote;
- i = pIdx;
- for ( j = 0; j < zIdent.Length; j++ )
- {
- if ( !sqlite3Isalnum( zIdent[j] ) && zIdent[j] != '_' )
- break;
- }
- needQuote = sqlite3Isdigit( zIdent[0] ) || sqlite3KeywordCode( zIdent, j ) != TK_ID;
- if ( !needQuote )
- {
- needQuote = ( j < zIdent.Length && zIdent[j] != 0 );
- }
- if ( needQuote )
- {
- if ( i == z.Length )
- z.Append( '\0' );
- z[i++] = '"';
- }
- for ( j = 0; j < zIdent.Length; j++ )
- {
- if ( i == z.Length )
- z.Append( '\0' );
- z[i++] = zIdent[j];
- if ( zIdent[j] == '"' )
- {
- if ( i == z.Length )
- z.Append( '\0' );
- z[i++] = '"';
+ /*
+ ** The first parameter is a pointer to an output buffer. The second
+ ** parameter is a pointer to an integer that contains the offset at
+ ** which to write into the output buffer. This function copies the
+ ** nul-terminated string pointed to by the third parameter, zSignedIdent,
+ ** to the specified offset in the buffer and updates *pIdx to refer
+ ** to the first byte after the last byte written before returning.
+ **
+ ** If the string zSignedIdent consists entirely of alpha-numeric
+ ** characters, does not begin with a digit and is not an SQL keyword,
+ ** then it is copied to the output buffer exactly as it is. Otherwise,
+ ** it is quoted using double-quotes.
+ */
+ static void identPut(StringBuilder z, ref int pIdx, string zSignedIdent) {
+ string zIdent = zSignedIdent;
+ int i;
+ int j;
+ bool needQuote;
+ i = pIdx;
+ for (j = 0; j < zIdent.Length; j++) {
+ if (!sqlite3Isalnum(zIdent[j]) && zIdent[j] != '_')
+ break;
+ }
+ needQuote = sqlite3Isdigit(zIdent[0]) || sqlite3KeywordCode(zIdent, j) != TK_ID;
+ if (!needQuote) {
+ needQuote = (j < zIdent.Length && zIdent[j] != 0);
+ }
+ if (needQuote) {
+ if (i == z.Length)
+ z.Append('\0');
+ z[i++] = '"';
+ }
+ for (j = 0; j < zIdent.Length; j++) {
+ if (i == z.Length)
+ z.Append('\0');
+ z[i++] = zIdent[j];
+ if (zIdent[j] == '"') {
+ if (i == z.Length)
+ z.Append('\0');
+ z[i++] = '"';
+ }
+ }
+ if (needQuote) {
+ if (i == z.Length)
+ z.Append('\0');
+ z[i++] = '"';
+ }
+ //z[i] = 0;
+ pIdx = i;
}
- }
- if ( needQuote )
- {
- if ( i == z.Length )
- z.Append( '\0' );
- z[i++] = '"';
- }
- //z[i] = 0;
- pIdx = i;
- }
- /*
- ** Generate a CREATE TABLE statement appropriate for the given
- ** table. Memory to hold the text of the statement is obtained
- ** from sqliteMalloc() and must be freed by the calling function.
- */
- static string createTableStmt( sqlite3 db, Table p )
- {
- int i, k, n;
- StringBuilder zStmt;
- string zSep;
- string zSep2;
- string zEnd;
- Column pCol;
- n = 0;
- for ( i = 0; i < p.nCol; i++ )
- {//, pCol++){
- pCol = p.aCol[i];
- n += identLength( pCol.zName ) + 5;
- }
- n += identLength( p.zName );
- if ( n < 50 )
- {
- zSep = "";
- zSep2 = ",";
- zEnd = ")";
- }
- else
- {
- zSep = "\n ";
- zSep2 = ",\n ";
- zEnd = "\n)";
- }
- n += 35 + 6 * p.nCol;
- zStmt = new StringBuilder( n );
- //zStmt = sqlite3DbMallocRaw(0, n);
- //if( zStmt==0 ){
- // db.mallocFailed = 1;
- // return 0;
- //}
- //sqlite3_snprintf(n, zStmt,"CREATE TABLE ");
- zStmt.Append( "CREATE TABLE " );
- k = sqlite3Strlen30( zStmt );
- identPut( zStmt, ref k, p.zName );
- zStmt.Append( '(' );//zStmt[k++] = '(';
- for ( i = 0; i < p.nCol; i++ )
- {//, pCol++){
- pCol = p.aCol[i];
- string[] azType = new string[] {
+ /*
+ ** Generate a CREATE TABLE statement appropriate for the given
+ ** table. Memory to hold the text of the statement is obtained
+ ** from sqliteMalloc() and must be freed by the calling function.
+ */
+ static string createTableStmt(sqlite3 db, Table p) {
+ int i, k, n;
+ StringBuilder zStmt;
+ string zSep;
+ string zSep2;
+ string zEnd;
+ Column pCol;
+ n = 0;
+ for (i = 0; i < p.nCol; i++) {//, pCol++){
+ pCol = p.aCol[i];
+ n += identLength(pCol.zName) + 5;
+ }
+ n += identLength(p.zName);
+ if (n < 50) {
+ zSep = "";
+ zSep2 = ",";
+ zEnd = ")";
+ } else {
+ zSep = "\n ";
+ zSep2 = ",\n ";
+ zEnd = "\n)";
+ }
+ n += 35 + 6 * p.nCol;
+ zStmt = new StringBuilder(n);
+ //zStmt = sqlite3DbMallocRaw(0, n);
+ //if( zStmt==0 ){
+ // db.mallocFailed = 1;
+ // return 0;
+ //}
+ //sqlite3_snprintf(n, zStmt,"CREATE TABLE ");
+ zStmt.Append("CREATE TABLE ");
+ k = sqlite3Strlen30(zStmt);
+ identPut(zStmt, ref k, p.zName);
+ zStmt.Append('(');//zStmt[k++] = '(';
+ for (i = 0; i < p.nCol; i++) {//, pCol++){
+ pCol = p.aCol[i];
+ string[] azType = new string[] {
/* SQLITE_AFF_TEXT */ " TEXT",
/* SQLITE_AFF_NONE */ "",
/* SQLITE_AFF_NUMERIC */ " NUM",
/* SQLITE_AFF_INTEGER */ " INT",
/* SQLITE_AFF_REAL */ " REAL"
};
- int len;
- string zType;
-
- zStmt.Append( zSep );// sqlite3_snprintf(n-k, zStmt[k], zSep);
- k = sqlite3Strlen30( zStmt );// k += strlen(zStmt[k]);
- zSep = zSep2;
- identPut( zStmt, ref k, pCol.zName );
- Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT >= 0 );
- Debug.Assert( pCol.affinity - SQLITE_AFF_TEXT < ArraySize( azType ) );
- testcase( pCol.affinity == SQLITE_AFF_TEXT );
- testcase( pCol.affinity == SQLITE_AFF_NONE );
- testcase( pCol.affinity == SQLITE_AFF_NUMERIC );
- testcase( pCol.affinity == SQLITE_AFF_INTEGER );
- testcase( pCol.affinity == SQLITE_AFF_REAL );
-
- zType = azType[pCol.affinity - SQLITE_AFF_TEXT];
- len = sqlite3Strlen30( zType );
- Debug.Assert( pCol.affinity == SQLITE_AFF_NONE
- || pCol.affinity == sqlite3AffinityType( zType ) );
- zStmt.Append( zType );// memcpy( &zStmt[k], zType, len );
- k += len;
- Debug.Assert( k <= n );
- }
- zStmt.Append( zEnd );//sqlite3_snprintf(n-k, zStmt[k], "%s", zEnd);
- return zStmt.ToString();
- }
-
- /*
- ** This routine is called to report the final ")" that terminates
- ** a CREATE TABLE statement.
- **
- ** The table structure that other action routines have been building
- ** is added to the internal hash tables, assuming no errors have
- ** occurred.
- **
- ** An entry for the table is made in the master table on disk, unless
- ** this is a temporary table or db.init.busy==1. When db.init.busy==1
- ** it means we are reading the sqlite_master table because we just
- ** connected to the database or because the sqlite_master table has
- ** recently changed, so the entry for this table already exists in
- ** the sqlite_master table. We do not want to create it again.
- **
- ** If the pSelect argument is not NULL, it means that this routine
- ** was called to create a table generated from a
- ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
- ** the new table will match the result set of the SELECT.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static void sqlite3EndTable( Parse pParse, Token pCons, Token pEnd, int null_4 )
- {
- sqlite3EndTable( pParse, pCons, pEnd, null );
- }
- static void sqlite3EndTable( Parse pParse, int null_2, int null_3, Select pSelect )
- {
- sqlite3EndTable( pParse, null, null, pSelect );
- }
-
- static void sqlite3EndTable(
- Parse pParse, /* Parse context */
- Token pCons, /* The ',' token after the last column defn. */
- Token pEnd, /* The final ')' token in the CREATE TABLE */
- Select pSelect /* Select from a "CREATE ... AS SELECT" */
- )
- {
- Table p;
- sqlite3 db = pParse.db;
- int iDb;
+ int len;
+ string zType;
+
+ zStmt.Append(zSep);// sqlite3_snprintf(n-k, zStmt[k], zSep);
+ k = sqlite3Strlen30(zStmt);// k += strlen(zStmt[k]);
+ zSep = zSep2;
+ identPut(zStmt, ref k, pCol.zName);
+ Debug.Assert(pCol.affinity - SQLITE_AFF_TEXT >= 0);
+ Debug.Assert(pCol.affinity - SQLITE_AFF_TEXT < ArraySize(azType));
+ testcase(pCol.affinity == SQLITE_AFF_TEXT);
+ testcase(pCol.affinity == SQLITE_AFF_NONE);
+ testcase(pCol.affinity == SQLITE_AFF_NUMERIC);
+ testcase(pCol.affinity == SQLITE_AFF_INTEGER);
+ testcase(pCol.affinity == SQLITE_AFF_REAL);
+
+ zType = azType[pCol.affinity - SQLITE_AFF_TEXT];
+ len = sqlite3Strlen30(zType);
+ Debug.Assert(pCol.affinity == SQLITE_AFF_NONE
+ || pCol.affinity == sqlite3AffinityType(zType));
+ zStmt.Append(zType);// memcpy( &zStmt[k], zType, len );
+ k += len;
+ Debug.Assert(k <= n);
+ }
+ zStmt.Append(zEnd);//sqlite3_snprintf(n-k, zStmt[k], "%s", zEnd);
+ return zStmt.ToString();
+ }
- if ( ( pEnd == null && pSelect == null ) /*|| db.mallocFailed != 0 */ )
- {
- return;
- }
- p = pParse.pNewTable;
- if ( p == null )
- return;
+ /*
+ ** This routine is called to report the final ")" that terminates
+ ** a CREATE TABLE statement.
+ **
+ ** The table structure that other action routines have been building
+ ** is added to the internal hash tables, assuming no errors have
+ ** occurred.
+ **
+ ** An entry for the table is made in the master table on disk, unless
+ ** this is a temporary table or db.init.busy==1. When db.init.busy==1
+ ** it means we are reading the sqlite_master table because we just
+ ** connected to the database or because the sqlite_master table has
+ ** recently changed, so the entry for this table already exists in
+ ** the sqlite_master table. We do not want to create it again.
+ **
+ ** If the pSelect argument is not NULL, it means that this routine
+ ** was called to create a table generated from a
+ ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
+ ** the new table will match the result set of the SELECT.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static void sqlite3EndTable(Parse pParse, Token pCons, Token pEnd, int null_4) {
+ sqlite3EndTable(pParse, pCons, pEnd, null);
+ }
+ static void sqlite3EndTable(Parse pParse, int null_2, int null_3, Select pSelect) {
+ sqlite3EndTable(pParse, null, null, pSelect);
+ }
+
+ static void sqlite3EndTable(
+ Parse pParse, /* Parse context */
+ Token pCons, /* The ',' token after the last column defn. */
+ Token pEnd, /* The final ')' token in the CREATE TABLE */
+ Select pSelect /* Select from a "CREATE ... AS SELECT" */
+ ) {
+ Table p;
+ sqlite3 db = pParse.db;
+ int iDb;
+
+ if ((pEnd == null && pSelect == null) /*|| db.mallocFailed != 0 */ ) {
+ return;
+ }
+ p = pParse.pNewTable;
+ if (p == null)
+ return;
- Debug.Assert( 0 == db.init.busy || pSelect == null );
+ Debug.Assert(0 == db.init.busy || pSelect == null);
- iDb = sqlite3SchemaToIndex( db, p.pSchema );
+ iDb = sqlite3SchemaToIndex(db, p.pSchema);
#if !SQLITE_OMIT_CHECK
- /* Resolve names in all CHECK constraint expressions.
-*/
- if ( p.pCheck != null )
- {
- SrcList sSrc; /* Fake SrcList for pParse.pNewTable */
- NameContext sNC; /* Name context for pParse.pNewTable */
-
- sNC = new NameContext();// memset(sNC, 0, sizeof(sNC));
- sSrc = new SrcList();// memset(sSrc, 0, sizeof(sSrc));
- sSrc.nSrc = 1;
- sSrc.a = new SrcList_item[1];
- sSrc.a[0] = new SrcList_item();
- sSrc.a[0].zName = p.zName;
- sSrc.a[0].pTab = p;
- sSrc.a[0].iCursor = -1;
- sNC.pParse = pParse;
- sNC.pSrcList = sSrc;
- sNC.isCheck = 1;
- if ( sqlite3ResolveExprNames( sNC, ref p.pCheck ) != 0 )
- {
- return;
- }
- }
+ /* Resolve names in all CHECK constraint expressions.
+ */
+ if (p.pCheck != null) {
+ SrcList sSrc; /* Fake SrcList for pParse.pNewTable */
+ NameContext sNC; /* Name context for pParse.pNewTable */
+
+ sNC = new NameContext();// memset(sNC, 0, sizeof(sNC));
+ sSrc = new SrcList();// memset(sSrc, 0, sizeof(sSrc));
+ sSrc.nSrc = 1;
+ sSrc.a = new SrcList_item[1];
+ sSrc.a[0] = new SrcList_item();
+ sSrc.a[0].zName = p.zName;
+ sSrc.a[0].pTab = p;
+ sSrc.a[0].iCursor = -1;
+ sNC.pParse = pParse;
+ sNC.pSrcList = sSrc;
+ sNC.isCheck = 1;
+ if (sqlite3ResolveExprNames(sNC, ref p.pCheck) != 0) {
+ return;
+ }
+ }
#endif // * !SQLITE_OMIT_CHECK) */
- /* If the db.init.busy is 1 it means we are reading the SQL off the
-** "sqlite_master" or "sqlite_temp_master" table on the disk.
-** So do not write to the disk again. Extract the root page number
-** for the table from the db.init.newTnum field. (The page number
-** should have been put there by the sqliteOpenCb routine.)
-*/
- if ( db.init.busy != 0 )
- {
- p.tnum = db.init.newTnum;
- }
-
- /* If not initializing, then create a record for the new table
- ** in the SQLITE_MASTER table of the database.
- **
- ** If this is a TEMPORARY table, write the entry into the auxiliary
- ** file instead of into the main database file.
+ /* If the db.init.busy is 1 it means we are reading the SQL off the
+ ** "sqlite_master" or "sqlite_temp_master" table on the disk.
+ ** So do not write to the disk again. Extract the root page number
+ ** for the table from the db.init.newTnum field. (The page number
+ ** should have been put there by the sqliteOpenCb routine.)
*/
- if ( 0 == db.init.busy )
- {
- int n;
- Vdbe v;
- String zType = ""; /* "view" or "table" */
- String zType2 = ""; /* "VIEW" or "TABLE" */
- String zStmt = ""; /* Text of the CREATE TABLE or CREATE VIEW statement */
-
- v = sqlite3GetVdbe( pParse );
- if ( NEVER( v == null ) )
- return;
-
- sqlite3VdbeAddOp1( v, OP_Close, 0 );
+ if (db.init.busy != 0) {
+ p.tnum = db.init.newTnum;
+ }
- /*
- ** Initialize zType for the new view or table.
- */
- if ( p.pSelect == null )
- {
- /* A regular table */
- zType = "table";
- zType2 = "TABLE";
+ /* If not initializing, then create a record for the new table
+ ** in the SQLITE_MASTER table of the database.
+ **
+ ** If this is a TEMPORARY table, write the entry into the auxiliary
+ ** file instead of into the main database file.
+ */
+ if (0 == db.init.busy) {
+ int n;
+ Vdbe v;
+ String zType = ""; /* "view" or "table" */
+ String zType2 = ""; /* "VIEW" or "TABLE" */
+ String zStmt = ""; /* Text of the CREATE TABLE or CREATE VIEW statement */
+
+ v = sqlite3GetVdbe(pParse);
+ if (NEVER(v == null))
+ return;
+
+ sqlite3VdbeAddOp1(v, OP_Close, 0);
+
+ /*
+ ** Initialize zType for the new view or table.
+ */
+ if (p.pSelect == null) {
+ /* A regular table */
+ zType = "table";
+ zType2 = "TABLE";
#if !SQLITE_OMIT_VIEW
- }
- else
- {
- /* A view */
- zType = "view";
- zType2 = "VIEW";
+ } else {
+ /* A view */
+ zType = "view";
+ zType2 = "VIEW";
#endif
- }
-
- /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
- ** statement to populate the new table. The root-page number for the
- ** new table is in register pParse->regRoot.
- **
- ** Once the SELECT has been coded by sqlite3Select(), it is in a
- ** suitable state to query for the column names and types to be used
- ** by the new table.
- **
- ** A shared-cache write-lock is not required to write to the new table,
- ** as a schema-lock must have already been obtained to create it. Since
- ** a schema-lock excludes all other database users, the write-lock would
- ** be redundant.
- */
- if ( pSelect != null )
- {
- SelectDest dest = new SelectDest();
- Table pSelTab;
-
- Debug.Assert( pParse.nTab == 1 );
- sqlite3VdbeAddOp3( v, OP_OpenWrite, 1, pParse.regRoot, iDb );
- sqlite3VdbeChangeP5( v, 1 );
- pParse.nTab = 2;
- sqlite3SelectDestInit( dest, SRT_Table, 1 );
- sqlite3Select( pParse, pSelect, ref dest );
- sqlite3VdbeAddOp1( v, OP_Close, 1 );
- if ( pParse.nErr == 0 )
- {
- pSelTab = sqlite3ResultSetOfSelect( pParse, pSelect );
- if ( pSelTab == null )
- return;
- Debug.Assert( p.aCol == null );
- p.nCol = pSelTab.nCol;
- p.aCol = pSelTab.aCol;
- pSelTab.nCol = 0;
- pSelTab.aCol = null;
- sqlite3DeleteTable( db, ref pSelTab );
- }
- }
-
- /* Compute the complete text of the CREATE statement */
- if ( pSelect != null )
- {
- zStmt = createTableStmt( db, p );
- }
- else
- {
- n = (int)( pParse.sNameToken.z.Length - pEnd.z.Length ) + 1;
- zStmt = sqlite3MPrintf( db,
- "CREATE %s %.*s", zType2, n, pParse.sNameToken.z
- );
- }
-
- /* A slot for the record has already been allocated in the
- ** SQLITE_MASTER table. We just need to update that slot with all
- ** the information we've collected.
- */
- sqlite3NestedParse( pParse,
- "UPDATE %Q.%s " +
- "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " +
- "WHERE rowid=#%d",
- db.aDb[iDb].zName, SCHEMA_TABLE( iDb ),
- zType,
- p.zName,
- p.zName,
- pParse.regRoot,
- zStmt,
- pParse.regRowid
- );
- sqlite3DbFree( db, ref zStmt );
- sqlite3ChangeCookie( pParse, iDb );
+ }
+
+ /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
+ ** statement to populate the new table. The root-page number for the
+ ** new table is in register pParse->regRoot.
+ **
+ ** Once the SELECT has been coded by sqlite3Select(), it is in a
+ ** suitable state to query for the column names and types to be used
+ ** by the new table.
+ **
+ ** A shared-cache write-lock is not required to write to the new table,
+ ** as a schema-lock must have already been obtained to create it. Since
+ ** a schema-lock excludes all other database users, the write-lock would
+ ** be redundant.
+ */
+ if (pSelect != null) {
+ SelectDest dest = new SelectDest();
+ Table pSelTab;
+
+ Debug.Assert(pParse.nTab == 1);
+ sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse.regRoot, iDb);
+ sqlite3VdbeChangeP5(v, 1);
+ pParse.nTab = 2;
+ sqlite3SelectDestInit(dest, SRT_Table, 1);
+ sqlite3Select(pParse, pSelect, ref dest);
+ sqlite3VdbeAddOp1(v, OP_Close, 1);
+ if (pParse.nErr == 0) {
+ pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
+ if (pSelTab == null)
+ return;
+ Debug.Assert(p.aCol == null);
+ p.nCol = pSelTab.nCol;
+ p.aCol = pSelTab.aCol;
+ pSelTab.nCol = 0;
+ pSelTab.aCol = null;
+ sqlite3DeleteTable(db, ref pSelTab);
+ }
+ }
+
+ /* Compute the complete text of the CREATE statement */
+ if (pSelect != null) {
+ zStmt = createTableStmt(db, p);
+ } else {
+ n = (int)(pParse.sNameToken.z.Length - pEnd.z.Length) + 1;
+ zStmt = sqlite3MPrintf(db,
+ "CREATE %s %.*s", zType2, n, pParse.sNameToken.z
+ );
+ }
+
+ /* A slot for the record has already been allocated in the
+ ** SQLITE_MASTER table. We just need to update that slot with all
+ ** the information we've collected.
+ */
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q.%s " +
+ "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q " +
+ "WHERE rowid=#%d",
+ db.aDb[iDb].zName, SCHEMA_TABLE(iDb),
+ zType,
+ p.zName,
+ p.zName,
+ pParse.regRoot,
+ zStmt,
+ pParse.regRowid
+ );
+ sqlite3DbFree(db, ref zStmt);
+ sqlite3ChangeCookie(pParse, iDb);
#if !SQLITE_OMIT_AUTOINCREMENT
- /* Check to see if we need to create an sqlite_sequence table for
-** keeping track of autoincrement keys.
-*/
- if ( ( p.tabFlags & TF_Autoincrement ) != 0 )
- {
- Db pDb = db.aDb[iDb];
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- if ( pDb.pSchema.pSeqTab == null )
- {
- sqlite3NestedParse( pParse,
- "CREATE TABLE %Q.sqlite_sequence(name,seq)",
- pDb.zName
- );
- }
- }
+ /* Check to see if we need to create an sqlite_sequence table for
+ ** keeping track of autoincrement keys.
+ */
+ if ((p.tabFlags & TF_Autoincrement) != 0) {
+ Db pDb = db.aDb[iDb];
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ if (pDb.pSchema.pSeqTab == null) {
+ sqlite3NestedParse(pParse,
+ "CREATE TABLE %Q.sqlite_sequence(name,seq)",
+ pDb.zName
+ );
+ }
+ }
#endif
- /* Reparse everything to update our internal data structures */
- sqlite3VdbeAddParseSchemaOp( v, iDb,
- sqlite3MPrintf( db, "tbl_name='%q'", p.zName ) );
- }
+ /* Reparse everything to update our internal data structures */
+ sqlite3VdbeAddParseSchemaOp(v, iDb,
+ sqlite3MPrintf(db, "tbl_name='%q'", p.zName));
+ }
- /* Add the table to the in-memory representation of the database.
- */
- if ( db.init.busy != 0 )
- {
- Table pOld;
- Schema pSchema = p.pSchema;
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- pOld = sqlite3HashInsert( ref pSchema.tblHash, p.zName,
- sqlite3Strlen30( p.zName ), p );
- if ( pOld != null )
- {
- Debug.Assert( p == pOld ); /* Malloc must have failed inside HashInsert() */
- // db.mallocFailed = 1;
- return;
- }
- pParse.pNewTable = null;
- db.nTable++;
- db.flags |= SQLITE_InternChanges;
+ /* Add the table to the in-memory representation of the database.
+ */
+ if (db.init.busy != 0) {
+ Table pOld;
+ Schema pSchema = p.pSchema;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ pOld = sqlite3HashInsert(ref pSchema.tblHash, p.zName,
+ sqlite3Strlen30(p.zName), p);
+ if (pOld != null) {
+ Debug.Assert(p == pOld); /* Malloc must have failed inside HashInsert() */
+ // db.mallocFailed = 1;
+ return;
+ }
+ pParse.pNewTable = null;
+ db.nTable++;
+ db.flags |= SQLITE_InternChanges;
#if !SQLITE_OMIT_ALTERTABLE
- if ( p.pSelect == null )
- {
- string zName = pParse.sNameToken.z;
- int nName;
- Debug.Assert( pSelect == null && pCons != null && pEnd != null );
- if ( pCons.z == null )
- {
- pCons = pEnd;
- }
- nName = zName.Length - pCons.z.Length;
- p.addColOffset = 13 + nName; // sqlite3Utf8CharLen(zName, nName);
- }
+ if (p.pSelect == null) {
+ string zName = pParse.sNameToken.z;
+ int nName;
+ Debug.Assert(pSelect == null && pCons != null && pEnd != null);
+ if (pCons.z == null) {
+ pCons = pEnd;
+ }
+ nName = zName.Length - pCons.z.Length;
+ p.addColOffset = 13 + nName; // sqlite3Utf8CharLen(zName, nName);
+ }
#endif
- }
- }
+ }
+ }
#if !SQLITE_OMIT_VIEW
- /*
-** The parser calls this routine in order to create a new VIEW
-*/
- static void sqlite3CreateView(
- Parse pParse, /* The parsing context */
- Token pBegin, /* The CREATE token that begins the statement */
- Token pName1, /* The token that holds the name of the view */
- Token pName2, /* The token that holds the name of the view */
- Select pSelect, /* A SELECT statement that will become the new view */
- int isTemp, /* TRUE for a TEMPORARY view */
- int noErr /* Suppress error messages if VIEW already exists */
- )
- {
- Table p;
- int n;
- string z;//string z;
- Token sEnd;
- DbFixer sFix = new DbFixer();
- Token pName = null;
- int iDb;
- sqlite3 db = pParse.db;
-
- if ( pParse.nVar > 0 )
- {
- sqlite3ErrorMsg( pParse, "parameters are not allowed in views" );
- sqlite3SelectDelete( db, ref pSelect );
- return;
- }
- sqlite3StartTable( pParse, pName1, pName2, isTemp, 1, 0, noErr );
- p = pParse.pNewTable;
- if ( p == null || pParse.nErr != 0 )
- {
- sqlite3SelectDelete( db, ref pSelect );
- return;
- }
- sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
- iDb = sqlite3SchemaToIndex( db, p.pSchema );
- if ( sqlite3FixInit( sFix, pParse, iDb, "view", pName ) != 0
- && sqlite3FixSelect( sFix, pSelect ) != 0
- )
- {
- sqlite3SelectDelete( db, ref pSelect );
- return;
- }
-
- /* Make a copy of the entire SELECT statement that defines the view.
- ** This will force all the Expr.token.z values to be dynamically
- ** allocated rather than point to the input string - which means that
- ** they will persist after the current sqlite3_exec() call returns.
- */
- p.pSelect = sqlite3SelectDup( db, pSelect, EXPRDUP_REDUCE );
- sqlite3SelectDelete( db, ref pSelect );
- //if ( db.mallocFailed != 0 )
- //{
- // return;
- //}
- if ( 0 == db.init.busy )
- {
- sqlite3ViewGetColumnNames( pParse, p );
- }
-
- /* Locate the end of the CREATE VIEW statement. Make sEnd point to
- ** the end.
- */
- sEnd = pParse.sLastToken;
- if ( ALWAYS( sEnd.z[0] != 0 ) && sEnd.z[0] != ';' )
- {
- sEnd.z = sEnd.z.Substring( sEnd.n );
- }
- sEnd.n = 0;
- n = (int)( pBegin.z.Length - sEnd.z.Length );//sEnd.z - pBegin.z;
- z = pBegin.z;
- while ( ALWAYS( n > 0 ) && sqlite3Isspace( z[n - 1] ) )
- {
- n--;
- }
- sEnd.z = z.Substring( n - 1 );
- sEnd.n = 1;
-
- /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
- sqlite3EndTable( pParse, null, sEnd, null );
- return;
- }
+ /*
+ ** The parser calls this routine in order to create a new VIEW
+ */
+ static void sqlite3CreateView(
+ Parse pParse, /* The parsing context */
+ Token pBegin, /* The CREATE token that begins the statement */
+ Token pName1, /* The token that holds the name of the view */
+ Token pName2, /* The token that holds the name of the view */
+ Select pSelect, /* A SELECT statement that will become the new view */
+ int isTemp, /* TRUE for a TEMPORARY view */
+ int noErr /* Suppress error messages if VIEW already exists */
+ ) {
+ Table p;
+ int n;
+ string z;//string z;
+ Token sEnd;
+ DbFixer sFix = new DbFixer();
+ Token pName = null;
+ int iDb;
+ sqlite3 db = pParse.db;
+
+ if (pParse.nVar > 0) {
+ sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
+ sqlite3SelectDelete(db, ref pSelect);
+ return;
+ }
+ sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
+ p = pParse.pNewTable;
+ if (p == null || pParse.nErr != 0) {
+ sqlite3SelectDelete(db, ref pSelect);
+ return;
+ }
+ sqlite3TwoPartName(pParse, pName1, pName2, ref pName);
+ iDb = sqlite3SchemaToIndex(db, p.pSchema);
+ if (sqlite3FixInit(sFix, pParse, iDb, "view", pName) != 0
+ && sqlite3FixSelect(sFix, pSelect) != 0
+ ) {
+ sqlite3SelectDelete(db, ref pSelect);
+ return;
+ }
+
+ /* Make a copy of the entire SELECT statement that defines the view.
+ ** This will force all the Expr.token.z values to be dynamically
+ ** allocated rather than point to the input string - which means that
+ ** they will persist after the current sqlite3_exec() call returns.
+ */
+ p.pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
+ sqlite3SelectDelete(db, ref pSelect);
+ //if ( db.mallocFailed != 0 )
+ //{
+ // return;
+ //}
+ if (0 == db.init.busy) {
+ sqlite3ViewGetColumnNames(pParse, p);
+ }
+
+ /* Locate the end of the CREATE VIEW statement. Make sEnd point to
+ ** the end.
+ */
+ sEnd = pParse.sLastToken;
+ if (ALWAYS(sEnd.z[0] != 0) && sEnd.z[0] != ';') {
+ sEnd.z = sEnd.z.Substring(sEnd.n);
+ }
+ sEnd.n = 0;
+ n = (int)(pBegin.z.Length - sEnd.z.Length);//sEnd.z - pBegin.z;
+ z = pBegin.z;
+ while (ALWAYS(n > 0) && sqlite3Isspace(z[n - 1])) {
+ n--;
+ }
+ sEnd.z = z.Substring(n - 1);
+ sEnd.n = 1;
+
+ /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
+ sqlite3EndTable(pParse, null, sEnd, null);
+ return;
+ }
#else
static void sqlite3CreateView(
Parse pParse, /* The parsing context */
@@ -2064,137 +1889,125 @@ static void sqlite3CreateView(
#endif // * SQLITE_OMIT_VIEW */
#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_VIRTUALTABLE
- /*
-** The Table structure pTable is really a VIEW. Fill in the names of
-** the columns of the view in the pTable structure. Return the number
-** of errors. If an error is seen leave an error message in pParse.zErrMsg.
-*/
- static int sqlite3ViewGetColumnNames( Parse pParse, Table pTable )
- {
- Table pSelTab; /* A fake table from which we get the result set */
- Select pSel; /* Copy of the SELECT that implements the view */
- int nErr = 0; /* Number of errors encountered */
- int n; /* Temporarily holds the number of cursors assigned */
- sqlite3 db = pParse.db; /* Database connection for malloc errors */
- dxAuth xAuth; //)(void*,int,const char*,const char*,const char*,const char);
+ /*
+ ** The Table structure pTable is really a VIEW. Fill in the names of
+ ** the columns of the view in the pTable structure. Return the number
+ ** of errors. If an error is seen leave an error message in pParse.zErrMsg.
+ */
+ static int sqlite3ViewGetColumnNames(Parse pParse, Table pTable) {
+ Table pSelTab; /* A fake table from which we get the result set */
+ Select pSel; /* Copy of the SELECT that implements the view */
+ int nErr = 0; /* Number of errors encountered */
+ int n; /* Temporarily holds the number of cursors assigned */
+ sqlite3 db = pParse.db; /* Database connection for malloc errors */
+ dxAuth xAuth; //)(void*,int,const char*,const char*,const char*,const char);
- Debug.Assert( pTable != null );
+ Debug.Assert(pTable != null);
#if !SQLITE_OMIT_VIRTUALTABLE
-if ( sqlite3VtabCallConnect( pParse, pTable )!=0 )
-{
-return SQLITE_ERROR;
-}
+ if (sqlite3VtabCallConnect(pParse, pTable) != 0) {
+ return SQLITE_ERROR;
+ }
#endif
- if ( IsVirtual( pTable ) )
- return 0;
+ if (IsVirtual(pTable))
+ return 0;
#if !SQLITE_OMIT_VIEW
- /* A positive nCol means the columns names for this view are
-** already known.
-*/
- if ( pTable.nCol > 0 )
- return 0;
-
- /* A negative nCol is a special marker meaning that we are currently
- ** trying to compute the column names. If we enter this routine with
- ** a negative nCol, it means two or more views form a loop, like this:
- **
- ** CREATE VIEW one AS SELECT * FROM two;
- ** CREATE VIEW two AS SELECT * FROM one;
- **
- ** Actually, the error above is now caught prior to reaching this point.
- ** But the following test is still important as it does come up
- ** in the following:
- **
- ** CREATE TABLE main.ex1(a);
- ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
- ** SELECT * FROM temp.ex1;
- */
- if ( pTable.nCol < 0 )
- {
- sqlite3ErrorMsg( pParse, "view %s is circularly defined", pTable.zName );
- return 1;
- }
- Debug.Assert( pTable.nCol >= 0 );
-
- /* If we get this far, it means we need to compute the table names.
- ** Note that the call to sqlite3ResultSetOfSelect() will expand any
- ** "*" elements in the results set of the view and will assign cursors
- ** to the elements of the FROM clause. But we do not want these changes
- ** to be permanent. So the computation is done on a copy of the SELECT
- ** statement that defines the view.
+ /* A positive nCol means the columns names for this view are
+ ** already known.
*/
- Debug.Assert( pTable.pSelect != null );
- pSel = sqlite3SelectDup( db, pTable.pSelect, 0 );
- if ( pSel != null )
- {
- u8 enableLookaside = db.lookaside.bEnabled;
- n = pParse.nTab;
- sqlite3SrcListAssignCursors( pParse, pSel.pSrc );
- pTable.nCol = -1;
- db.lookaside.bEnabled = 0;
+ if (pTable.nCol > 0)
+ return 0;
+
+ /* A negative nCol is a special marker meaning that we are currently
+ ** trying to compute the column names. If we enter this routine with
+ ** a negative nCol, it means two or more views form a loop, like this:
+ **
+ ** CREATE VIEW one AS SELECT * FROM two;
+ ** CREATE VIEW two AS SELECT * FROM one;
+ **
+ ** Actually, the error above is now caught prior to reaching this point.
+ ** But the following test is still important as it does come up
+ ** in the following:
+ **
+ ** CREATE TABLE main.ex1(a);
+ ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
+ ** SELECT * FROM temp.ex1;
+ */
+ if (pTable.nCol < 0) {
+ sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable.zName);
+ return 1;
+ }
+ Debug.Assert(pTable.nCol >= 0);
+
+ /* If we get this far, it means we need to compute the table names.
+ ** Note that the call to sqlite3ResultSetOfSelect() will expand any
+ ** "*" elements in the results set of the view and will assign cursors
+ ** to the elements of the FROM clause. But we do not want these changes
+ ** to be permanent. So the computation is done on a copy of the SELECT
+ ** statement that defines the view.
+ */
+ Debug.Assert(pTable.pSelect != null);
+ pSel = sqlite3SelectDup(db, pTable.pSelect, 0);
+ if (pSel != null) {
+ u8 enableLookaside = db.lookaside.bEnabled;
+ n = pParse.nTab;
+ sqlite3SrcListAssignCursors(pParse, pSel.pSrc);
+ pTable.nCol = -1;
+ db.lookaside.bEnabled = 0;
#if !SQLITE_OMIT_AUTHORIZATION
xAuth = db.xAuth;
db.xAuth = 0;
pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
db.xAuth = xAuth;
#else
- pSelTab = sqlite3ResultSetOfSelect( pParse, pSel );
+ pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
#endif
- db.lookaside.bEnabled = enableLookaside;
- pParse.nTab = n;
- if ( pSelTab != null )
- {
- Debug.Assert( pTable.aCol == null );
- pTable.nCol = pSelTab.nCol;
- pTable.aCol = pSelTab.aCol;
- pSelTab.nCol = 0;
- pSelTab.aCol = null;
- sqlite3DeleteTable( db, ref pSelTab );
- Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pTable.pSchema ) );
- pTable.pSchema.flags |= DB_UnresetViews;
- }
- else
- {
- pTable.nCol = 0;
- nErr++;
- }
- sqlite3SelectDelete( db, ref pSel );
- }
- else
- {
- nErr++;
- }
+ db.lookaside.bEnabled = enableLookaside;
+ pParse.nTab = n;
+ if (pSelTab != null) {
+ Debug.Assert(pTable.aCol == null);
+ pTable.nCol = pSelTab.nCol;
+ pTable.aCol = pSelTab.aCol;
+ pSelTab.nCol = 0;
+ pSelTab.aCol = null;
+ sqlite3DeleteTable(db, ref pSelTab);
+ Debug.Assert(sqlite3SchemaMutexHeld(db, 0, pTable.pSchema));
+ pTable.pSchema.flags |= DB_UnresetViews;
+ } else {
+ pTable.nCol = 0;
+ nErr++;
+ }
+ sqlite3SelectDelete(db, ref pSel);
+ } else {
+ nErr++;
+ }
#endif // * SQLITE_OMIT_VIEW */
- return nErr;
- }
+ return nErr;
+ }
#endif // * !SQLITE_OMIT_VIEW) || !SQLITE_OMIT_VIRTUALTABLE) */
#if !SQLITE_OMIT_VIEW
- /*
-** Clear the column names from every VIEW in database idx.
-*/
- static void sqliteViewResetAll( sqlite3 db, int idx )
- {
- HashElem i;
- Debug.Assert( sqlite3SchemaMutexHeld( db, idx, null ) );
- if ( !DbHasProperty( db, idx, DB_UnresetViews ) )
- return;
- //for(i=sqliteHashFirst(&db.aDb[idx].pSchema.tblHash); i;i=sqliteHashNext(i)){
- for ( i = db.aDb[idx].pSchema.tblHash.first; i != null; i = i.next )
- {
- Table pTab = (Table)i.data;// sqliteHashData( i );
- if ( pTab.pSelect != null )
- {
- sqliteDeleteColumnNames( db, pTab );
- pTab.aCol = null;
- pTab.nCol = 0;
-
+ /*
+ ** Clear the column names from every VIEW in database idx.
+ */
+ static void sqliteViewResetAll(sqlite3 db, int idx) {
+ HashElem i;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, idx, null));
+ if (!DbHasProperty(db, idx, DB_UnresetViews))
+ return;
+ //for(i=sqliteHashFirst(&db.aDb[idx].pSchema.tblHash); i;i=sqliteHashNext(i)){
+ for (i = db.aDb[idx].pSchema.tblHash.first; i != null; i = i.next) {
+ Table pTab = (Table)i.data;// sqliteHashData( i );
+ if (pTab.pSelect != null) {
+ sqliteDeleteColumnNames(db, pTab);
+ pTab.aCol = null;
+ pTab.nCol = 0;
+
+ }
+ }
+ DbClearProperty(db, idx, DB_UnresetViews);
}
- }
- DbClearProperty( db, idx, DB_UnresetViews );
- }
#else
//# define sqliteViewResetAll(A,B)
static void sqliteViewResetAll( sqlite3 A, int B )
@@ -2202,92 +2015,87 @@ static void sqliteViewResetAll( sqlite3 A, int B )
}
#endif // * SQLITE_OMIT_VIEW */
- /*
-** This function is called by the VDBE to adjust the internal schema
-** used by SQLite when the btree layer moves a table root page. The
-** root-page of a table or index in database iDb has changed from iFrom
-** to iTo.
-**
-** Ticket #1728: The symbol table might still contain information
-** on tables and/or indices that are the process of being deleted.
-** If you are unlucky, one of those deleted indices or tables might
-** have the same rootpage number as the real table or index that is
-** being moved. So we cannot stop searching after the first match
-** because the first match might be for one of the deleted indices
-** or tables and not the table/index that is actually being moved.
-** We must continue looping until all tables and indices with
-** rootpage==iFrom have been converted to have a rootpage of iTo
-** in order to be certain that we got the right one.
-*/
+ /*
+ ** This function is called by the VDBE to adjust the internal schema
+ ** used by SQLite when the btree layer moves a table root page. The
+ ** root-page of a table or index in database iDb has changed from iFrom
+ ** to iTo.
+ **
+ ** Ticket #1728: The symbol table might still contain information
+ ** on tables and/or indices that are the process of being deleted.
+ ** If you are unlucky, one of those deleted indices or tables might
+ ** have the same rootpage number as the real table or index that is
+ ** being moved. So we cannot stop searching after the first match
+ ** because the first match might be for one of the deleted indices
+ ** or tables and not the table/index that is actually being moved.
+ ** We must continue looping until all tables and indices with
+ ** rootpage==iFrom have been converted to have a rootpage of iTo
+ ** in order to be certain that we got the right one.
+ */
#if !SQLITE_OMIT_AUTOVACUUM
- static void sqlite3RootPageMoved( sqlite3 db, int iDb, int iFrom, int iTo )
- {
- HashElem pElem;
- Hash pHash;
- Db pDb;
-
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- pDb = db.aDb[iDb];
-
- pHash = pDb.pSchema.tblHash;
- for ( pElem = pHash.first; pElem != null; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) )
- {
- Table pTab = (Table)pElem.data;// sqliteHashData( pElem );
- if ( pTab.tnum == iFrom )
- {
- pTab.tnum = iTo;
- }
- }
- pHash = pDb.pSchema.idxHash;
- for ( pElem = pHash.first; pElem != null; pElem = pElem.next )// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) )
- {
- Index pIdx = (Index)pElem.data;// sqliteHashData( pElem );
- if ( pIdx.tnum == iFrom )
- {
- pIdx.tnum = iTo;
+ static void sqlite3RootPageMoved(sqlite3 db, int iDb, int iFrom, int iTo) {
+ HashElem pElem;
+ Hash pHash;
+ Db pDb;
+
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ pDb = db.aDb[iDb];
+
+ pHash = pDb.pSchema.tblHash;
+ for (pElem = pHash.first; pElem != null; pElem = pElem.next)// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) )
+ {
+ Table pTab = (Table)pElem.data;// sqliteHashData( pElem );
+ if (pTab.tnum == iFrom) {
+ pTab.tnum = iTo;
+ }
+ }
+ pHash = pDb.pSchema.idxHash;
+ for (pElem = pHash.first; pElem != null; pElem = pElem.next)// ( pElem = sqliteHashFirst( pHash ) ; pElem ; pElem = sqliteHashNext( pElem ) )
+ {
+ Index pIdx = (Index)pElem.data;// sqliteHashData( pElem );
+ if (pIdx.tnum == iFrom) {
+ pIdx.tnum = iTo;
+ }
+ }
}
- }
- }
#endif
- /*
-** Write code to erase the table with root-page iTable from database iDb.
-** Also write code to modify the sqlite_master table and internal schema
-** if a root-page of another table is moved by the btree-layer whilst
-** erasing iTable (this can happen with an auto-vacuum database).
-*/
- static void destroyRootPage( Parse pParse, int iTable, int iDb )
- {
- Vdbe v = sqlite3GetVdbe( pParse );
- int r1 = sqlite3GetTempReg( pParse );
- sqlite3VdbeAddOp3( v, OP_Destroy, iTable, r1, iDb );
- sqlite3MayAbort( pParse );
+ /*
+ ** Write code to erase the table with root-page iTable from database iDb.
+ ** Also write code to modify the sqlite_master table and internal schema
+ ** if a root-page of another table is moved by the btree-layer whilst
+ ** erasing iTable (this can happen with an auto-vacuum database).
+ */
+ static void destroyRootPage(Parse pParse, int iTable, int iDb) {
+ Vdbe v = sqlite3GetVdbe(pParse);
+ int r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
+ sqlite3MayAbort(pParse);
#if !SQLITE_OMIT_AUTOVACUUM
- /* OP_Destroy stores an in integer r1. If this integer
-** is non-zero, then it is the root page number of a table moved to
-** location iTable. The following code modifies the sqlite_master table to
-** reflect this.
-**
-** The "#NNN" in the SQL is a special constant that means whatever value
-** is in register NNN. See grammar rules associated with the TK_REGISTER
-** token for additional information.
-*/
- sqlite3NestedParse( pParse,
- "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
- pParse.db.aDb[iDb].zName, SCHEMA_TABLE( iDb ), iTable, r1, r1 );
+ /* OP_Destroy stores an in integer r1. If this integer
+ ** is non-zero, then it is the root page number of a table moved to
+ ** location iTable. The following code modifies the sqlite_master table to
+ ** reflect this.
+ **
+ ** The "#NNN" in the SQL is a special constant that means whatever value
+ ** is in register NNN. See grammar rules associated with the TK_REGISTER
+ ** token for additional information.
+ */
+ sqlite3NestedParse(pParse,
+ "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
+ pParse.db.aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
#endif
- sqlite3ReleaseTempReg( pParse, r1 );
- }
+ sqlite3ReleaseTempReg(pParse, r1);
+ }
- /*
- ** Write VDBE code to erase table pTab and all associated indices on disk.
- ** Code to update the sqlite_master tables and internal schema definitions
- ** in case a root-page belonging to another table is moved by the btree layer
- ** is also added (this can happen with an auto-vacuum database).
- */
- static void destroyTable( Parse pParse, Table pTab )
- {
-#if SQLITE_OMIT_AUTOVACUUM
+ /*
+ ** Write VDBE code to erase table pTab and all associated indices on disk.
+ ** Code to update the sqlite_master tables and internal schema definitions
+ ** in case a root-page belonging to another table is moved by the btree layer
+ ** is also added (this can happen with an auto-vacuum database).
+ */
+ static void destroyTable(Parse pParse, Table pTab) {
+#if SQLITE_OMIT_AUTOVACUUM
Index pIdx;
int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
destroyRootPage( pParse, pTab.tnum, iDb );
@@ -2296,97 +2104,87 @@ static void destroyTable( Parse pParse, Table pTab )
destroyRootPage( pParse, pIdx.tnum, iDb );
}
#else
- /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
-** is not defined), then it is important to call OP_Destroy on the
-** table and index root-pages in order, starting with the numerically
-** largest root-page number. This guarantees that none of the root-pages
-** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
-** following were coded:
-**
-** OP_Destroy 4 0
-** ...
-** OP_Destroy 5 0
-**
-** and root page 5 happened to be the largest root-page number in the
-** database, then root page 5 would be moved to page 4 by the
-** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
-** a free-list page.
-*/
- int iTab = pTab.tnum;
- int iDestroyed = 0;
-
- while ( true )
- {
- Index pIdx;
- int iLargest = 0;
-
- if ( iDestroyed == 0 || iTab < iDestroyed )
- {
- iLargest = iTab;
- }
- for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- int iIdx = pIdx.tnum;
- Debug.Assert( pIdx.pSchema == pTab.pSchema );
- if ( ( iDestroyed == 0 || ( iIdx < iDestroyed ) ) && iIdx > iLargest )
- {
- iLargest = iIdx;
- }
- }
- if ( iLargest == 0 )
- {
- return;
- }
- else
- {
- int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
- destroyRootPage( pParse, iLargest, iDb );
- iDestroyed = iLargest;
- }
- }
+ /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
+ ** is not defined), then it is important to call OP_Destroy on the
+ ** table and index root-pages in order, starting with the numerically
+ ** largest root-page number. This guarantees that none of the root-pages
+ ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
+ ** following were coded:
+ **
+ ** OP_Destroy 4 0
+ ** ...
+ ** OP_Destroy 5 0
+ **
+ ** and root page 5 happened to be the largest root-page number in the
+ ** database, then root page 5 would be moved to page 4 by the
+ ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
+ ** a free-list page.
+ */
+ int iTab = pTab.tnum;
+ int iDestroyed = 0;
+
+ while (true) {
+ Index pIdx;
+ int iLargest = 0;
+
+ if (iDestroyed == 0 || iTab < iDestroyed) {
+ iLargest = iTab;
+ }
+ for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ int iIdx = pIdx.tnum;
+ Debug.Assert(pIdx.pSchema == pTab.pSchema);
+ if ((iDestroyed == 0 || (iIdx < iDestroyed)) && iIdx > iLargest) {
+ iLargest = iIdx;
+ }
+ }
+ if (iLargest == 0) {
+ return;
+ } else {
+ int iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
+ destroyRootPage(pParse, iLargest, iDb);
+ iDestroyed = iLargest;
+ }
+ }
#endif
- }
+ }
- /*
- ** This routine is called to do the work of a DROP TABLE statement.
- ** pName is the name of the table to be dropped.
- */
- static void sqlite3DropTable( Parse pParse, SrcList pName, int isView, int noErr )
- {
- Table pTab;
- Vdbe v;
- sqlite3 db = pParse.db;
- int iDb;
-
- //if ( db.mallocFailed != 0 )
- //{
- // goto exit_drop_table;
- //}
- Debug.Assert( pParse.nErr == 0 );
- Debug.Assert( pName.nSrc == 1 );
- if ( noErr != 0 )
- db.suppressErr++;
- pTab = sqlite3LocateTable( pParse, isView,
- pName.a[0].zName, pName.a[0].zDatabase );
- if ( noErr != 0 )
- db.suppressErr--;
-
- if ( pTab == null )
- {
- if ( noErr != 0)
- sqlite3CodeVerifyNamedSchema( pParse, pName.a[0].zDatabase );
- goto exit_drop_table;
- }
- iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
- Debug.Assert( iDb >= 0 && iDb < db.nDb );
-
- /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
- ** it is initialized.
- */
- if ( IsVirtual( pTab ) && sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
- {
- goto exit_drop_table;
- }
+ /*
+ ** This routine is called to do the work of a DROP TABLE statement.
+ ** pName is the name of the table to be dropped.
+ */
+ static void sqlite3DropTable(Parse pParse, SrcList pName, int isView, int noErr) {
+ Table pTab;
+ Vdbe v;
+ sqlite3 db = pParse.db;
+ int iDb;
+
+ //if ( db.mallocFailed != 0 )
+ //{
+ // goto exit_drop_table;
+ //}
+ Debug.Assert(pParse.nErr == 0);
+ Debug.Assert(pName.nSrc == 1);
+ if (noErr != 0)
+ db.suppressErr++;
+ pTab = sqlite3LocateTable(pParse, isView,
+ pName.a[0].zName, pName.a[0].zDatabase);
+ if (noErr != 0)
+ db.suppressErr--;
+
+ if (pTab == null) {
+ if (noErr != 0)
+ sqlite3CodeVerifyNamedSchema(pParse, pName.a[0].zDatabase);
+ goto exit_drop_table;
+ }
+ iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
+ Debug.Assert(iDb >= 0 && iDb < db.nDb);
+
+ /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
+ ** it is initialized.
+ */
+ if (IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) != 0) {
+ goto exit_drop_table;
+ }
#if !SQLITE_OMIT_AUTHORIZATION
{
int code;
@@ -2420,316 +2218,285 @@ static void sqlite3DropTable( Parse pParse, SrcList pName, int isView, int noErr
}
}
#endif
- if ( pTab.zName.StartsWith( "sqlite_", System.StringComparison.OrdinalIgnoreCase ) )
- {
- sqlite3ErrorMsg( pParse, "table %s may not be dropped", pTab.zName );
- goto exit_drop_table;
- }
+ if (pTab.zName.StartsWith("sqlite_", System.StringComparison.OrdinalIgnoreCase)) {
+ sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab.zName);
+ goto exit_drop_table;
+ }
#if !SQLITE_OMIT_VIEW
- /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
-** on a table.
-*/
- if ( isView != 0 && pTab.pSelect == null )
- {
- sqlite3ErrorMsg( pParse, "use DROP TABLE to delete table %s", pTab.zName );
- goto exit_drop_table;
- }
- if ( 0 == isView && pTab.pSelect != null )
- {
- sqlite3ErrorMsg( pParse, "use DROP VIEW to delete view %s", pTab.zName );
- goto exit_drop_table;
- }
+ /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
+ ** on a table.
+ */
+ if (isView != 0 && pTab.pSelect == null) {
+ sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab.zName);
+ goto exit_drop_table;
+ }
+ if (0 == isView && pTab.pSelect != null) {
+ sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab.zName);
+ goto exit_drop_table;
+ }
#endif
- /* Generate code to remove the table from the master table
-** on disk.
-*/
- v = sqlite3GetVdbe( pParse );
- if ( v != null )
- {
- Trigger pTrigger;
- Db pDb = db.aDb[iDb];
- sqlite3BeginWriteOperation( pParse, 1, iDb );
+ /* Generate code to remove the table from the master table
+ ** on disk.
+ */
+ v = sqlite3GetVdbe(pParse);
+ if (v != null) {
+ Trigger pTrigger;
+ Db pDb = db.aDb[iDb];
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
#if !SQLITE_OMIT_VIRTUALTABLE
- if ( IsVirtual( pTab ) )
- {
- sqlite3VdbeAddOp0( v, OP_VBegin );
- }
+ if (IsVirtual(pTab)) {
+ sqlite3VdbeAddOp0(v, OP_VBegin);
+ }
#endif
- sqlite3FkDropTable( pParse, pName, pTab );
-
- /* Drop all triggers associated with the table being dropped. Code
- ** is generated to remove entries from sqlite_master and/or
- ** sqlite_temp_master if required.
- */
- pTrigger = sqlite3TriggerList( pParse, pTab );
- while ( pTrigger != null )
- {
- Debug.Assert( pTrigger.pSchema == pTab.pSchema ||
- pTrigger.pSchema == db.aDb[1].pSchema );
- sqlite3DropTriggerPtr( pParse, pTrigger );
- pTrigger = pTrigger.pNext;
- }
+ sqlite3FkDropTable(pParse, pName, pTab);
+
+ /* Drop all triggers associated with the table being dropped. Code
+ ** is generated to remove entries from sqlite_master and/or
+ ** sqlite_temp_master if required.
+ */
+ pTrigger = sqlite3TriggerList(pParse, pTab);
+ while (pTrigger != null) {
+ Debug.Assert(pTrigger.pSchema == pTab.pSchema ||
+ pTrigger.pSchema == db.aDb[1].pSchema);
+ sqlite3DropTriggerPtr(pParse, pTrigger);
+ pTrigger = pTrigger.pNext;
+ }
#if !SQLITE_OMIT_AUTOINCREMENT
- /* Remove any entries of the sqlite_sequence table associated with
-** the table being dropped. This is done before the table is dropped
-** at the btree level, in case the sqlite_sequence table needs to
-** move as a result of the drop (can happen in auto-vacuum mode).
-*/
- if ( ( pTab.tabFlags & TF_Autoincrement ) != 0 )
- {
- sqlite3NestedParse( pParse,
- "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
- pDb.zName, pTab.zName
- );
- }
+ /* Remove any entries of the sqlite_sequence table associated with
+ ** the table being dropped. This is done before the table is dropped
+ ** at the btree level, in case the sqlite_sequence table needs to
+ ** move as a result of the drop (can happen in auto-vacuum mode).
+ */
+ if ((pTab.tabFlags & TF_Autoincrement) != 0) {
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %s.sqlite_sequence WHERE name=%Q",
+ pDb.zName, pTab.zName
+ );
+ }
#endif
- /* Drop all SQLITE_MASTER table and index entries that refer to the
-** table. The program name loops through the master table and deletes
-** every row that refers to a table of the same name as the one being
-** dropped. Triggers are handled seperately because a trigger can be
-** created in the temp database that refers to a table in another
-** database.
-*/
- sqlite3NestedParse( pParse,
- "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
- pDb.zName, SCHEMA_TABLE( iDb ), pTab.zName );
-
- /* Drop any statistics from the sqlite_stat1 table, if it exists */
- if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null )
- {
- sqlite3NestedParse( pParse,
- "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb.zName, pTab.zName
- );
- }
+ /* Drop all SQLITE_MASTER table and index entries that refer to the
+ ** table. The program name loops through the master table and deletes
+ ** every row that refers to a table of the same name as the one being
+ ** dropped. Triggers are handled seperately because a trigger can be
+ ** created in the temp database that refers to a table in another
+ ** database.
+ */
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
+ pDb.zName, SCHEMA_TABLE(iDb), pTab.zName);
+
+ /* Drop any statistics from the sqlite_stat1 table, if it exists */
+ if (sqlite3FindTable(db, "sqlite_stat1", db.aDb[iDb].zName) != null) {
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q", pDb.zName, pTab.zName
+ );
+ }
+
+ if (0 == isView && !IsVirtual(pTab)) {
+ destroyTable(pParse, pTab);
+ }
+
+ /* Remove the table entry from SQLite's internal schema and modify
+ ** the schema cookie.
+ */
+ if (IsVirtual(pTab)) {
+ sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab.zName, 0);
+ }
+ sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab.zName, 0);
+ sqlite3ChangeCookie(pParse, iDb);
+ }
+ sqliteViewResetAll(db, iDb);
- if ( 0 == isView && !IsVirtual( pTab ) )
- {
- destroyTable( pParse, pTab );
+ exit_drop_table:
+ sqlite3SrcListDelete(db, ref pName);
}
- /* Remove the table entry from SQLite's internal schema and modify
- ** the schema cookie.
+ /*
+ ** This routine is called to create a new foreign key on the table
+ ** currently under construction. pFromCol determines which columns
+ ** in the current table point to the foreign key. If pFromCol==0 then
+ ** connect the key to the last column inserted. pTo is the name of
+ ** the table referred to. pToCol is a list of tables in the other
+ ** pTo table that the foreign key points to. flags contains all
+ ** information about the conflict resolution algorithms specified
+ ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
+ **
+ ** An FKey structure is created and added to the table currently
+ ** under construction in the pParse.pNewTable field.
+ **
+ ** The foreign key is set for IMMEDIATE processing. A subsequent call
+ ** to sqlite3DeferForeignKey() might change this to DEFERRED.
*/
- if ( IsVirtual( pTab ) )
- {
- sqlite3VdbeAddOp4( v, OP_VDestroy, iDb, 0, 0, pTab.zName, 0 );
- }
- sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 );
- sqlite3ChangeCookie( pParse, iDb );
- }
- sqliteViewResetAll( db, iDb );
-
-exit_drop_table:
- sqlite3SrcListDelete( db, ref pName );
- }
-
- /*
- ** This routine is called to create a new foreign key on the table
- ** currently under construction. pFromCol determines which columns
- ** in the current table point to the foreign key. If pFromCol==0 then
- ** connect the key to the last column inserted. pTo is the name of
- ** the table referred to. pToCol is a list of tables in the other
- ** pTo table that the foreign key points to. flags contains all
- ** information about the conflict resolution algorithms specified
- ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
- **
- ** An FKey structure is created and added to the table currently
- ** under construction in the pParse.pNewTable field.
- **
- ** The foreign key is set for IMMEDIATE processing. A subsequent call
- ** to sqlite3DeferForeignKey() might change this to DEFERRED.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static void sqlite3CreateForeignKey( Parse pParse, int null_2, Token pTo, ExprList pToCol, int flags )
- {
- sqlite3CreateForeignKey( pParse, null, pTo, pToCol, flags );
- }
- static void sqlite3CreateForeignKey(
- Parse pParse, /* Parsing context */
- ExprList pFromCol, /* Columns in this table that point to other table */
- Token pTo, /* Name of the other table */
- ExprList pToCol, /* Columns in the other table */
- int flags /* Conflict resolution algorithms. */
- )
- {
- sqlite3 db = pParse.db;
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static void sqlite3CreateForeignKey(Parse pParse, int null_2, Token pTo, ExprList pToCol, int flags) {
+ sqlite3CreateForeignKey(pParse, null, pTo, pToCol, flags);
+ }
+ static void sqlite3CreateForeignKey(
+ Parse pParse, /* Parsing context */
+ ExprList pFromCol, /* Columns in this table that point to other table */
+ Token pTo, /* Name of the other table */
+ ExprList pToCol, /* Columns in the other table */
+ int flags /* Conflict resolution algorithms. */
+ ) {
+ sqlite3 db = pParse.db;
#if !SQLITE_OMIT_FOREIGN_KEY
- FKey pFKey = null;
- FKey pNextTo;
- Table p = pParse.pNewTable;
- int nByte;
- int i;
- int nCol;
- //string z;
-
- Debug.Assert( pTo != null );
- if ( p == null || IN_DECLARE_VTAB( pParse ) )
- goto fk_end;
- if ( pFromCol == null )
- {
- int iCol = p.nCol - 1;
- if ( NEVER( iCol < 0 ) )
- goto fk_end;
- if ( pToCol != null && pToCol.nExpr != 1 )
- {
- sqlite3ErrorMsg( pParse, "foreign key on %s" +
- " should reference only one column of table %T",
- p.aCol[iCol].zName, pTo );
- goto fk_end;
- }
- nCol = 1;
- }
- else if ( pToCol != null && pToCol.nExpr != pFromCol.nExpr )
- {
- sqlite3ErrorMsg( pParse,
- "number of columns in foreign key does not match the number of " +
- "columns in the referenced table" );
- goto fk_end;
- }
- else
- {
- nCol = pFromCol.nExpr;
- }
- //nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey.aCol[0]) + pTo.n + 1;
- //if( pToCol ){
- // for(i=0; ia[i].zName) + 1;
- // }
- //}
- pFKey = new FKey();//sqlite3DbMallocZero(db, nByte );
- if ( pFKey == null )
- {
- goto fk_end;
- }
- pFKey.pFrom = p;
- pFKey.pNextFrom = p.pFKey;
- //z = pFKey.aCol[nCol].zCol;
- pFKey.aCol = new FKey.sColMap[nCol];// z;
- pFKey.aCol[0] = new FKey.sColMap();
- pFKey.zTo = pTo.z.Substring( 0, pTo.n ); //memcpy( z, pTo.z, pTo.n );
- //z[pTo.n] = 0;
- sqlite3Dequote( ref pFKey.zTo );
- //z += pTo.n + 1;
- pFKey.nCol = nCol;
- if ( pFromCol == null )
- {
- pFKey.aCol[0].iFrom = p.nCol - 1;
- }
- else
- {
- for ( i = 0; i < nCol; i++ )
- {
- if ( pFKey.aCol[i] == null )
- pFKey.aCol[i] = new FKey.sColMap();
- int j;
- for ( j = 0; j < p.nCol; j++ )
- {
- if ( p.aCol[j].zName.Equals( pFromCol.a[i].zName, StringComparison.OrdinalIgnoreCase ) )
- {
- pFKey.aCol[i].iFrom = j;
- break;
- }
- }
- if ( j >= p.nCol )
- {
- sqlite3ErrorMsg( pParse,
- "unknown column \"%s\" in foreign key definition",
- pFromCol.a[i].zName );
- goto fk_end;
- }
- }
- }
- if ( pToCol != null )
- {
- for ( i = 0; i < nCol; i++ )
- {
- ////int n = sqlite3Strlen30( pToCol.a[i].zName );
- if ( pFKey.aCol[i] == null )
- pFKey.aCol[i] = new FKey.sColMap();
- pFKey.aCol[i].zCol = pToCol.a[i].zName;
- //memcpy( z, pToCol.a[i].zName, n );
- //z[n] = 0;
- //z += n + 1;
- }
- }
- pFKey.isDeferred = 0;
- pFKey.aAction[0] = (u8)( flags & 0xff ); /* ON DELETE action */
- pFKey.aAction[1] = (u8)( ( flags >> 8 ) & 0xff ); /* ON UPDATE action */
-
- Debug.Assert( sqlite3SchemaMutexHeld( db, 0, p.pSchema ) );
- pNextTo = sqlite3HashInsert( ref p.pSchema.fkeyHash,
- pFKey.zTo, sqlite3Strlen30( pFKey.zTo ), pFKey
- );
- //if( pNextTo==pFKey ){
- // db.mallocFailed = 1;
- // goto fk_end;
- //}
- if ( pNextTo != null )
- {
- Debug.Assert( pNextTo.pPrevTo == null );
- pFKey.pNextTo = pNextTo;
- pNextTo.pPrevTo = pFKey;
- }
- /* Link the foreign key to the table as the last step.
- */
- p.pFKey = pFKey;
- pFKey = null;
+ FKey pFKey = null;
+ FKey pNextTo;
+ Table p = pParse.pNewTable;
+ int nByte;
+ int i;
+ int nCol;
+ //string z;
+
+ Debug.Assert(pTo != null);
+ if (p == null || IN_DECLARE_VTAB(pParse))
+ goto fk_end;
+ if (pFromCol == null) {
+ int iCol = p.nCol - 1;
+ if (NEVER(iCol < 0))
+ goto fk_end;
+ if (pToCol != null && pToCol.nExpr != 1) {
+ sqlite3ErrorMsg(pParse, "foreign key on %s" +
+ " should reference only one column of table %T",
+ p.aCol[iCol].zName, pTo);
+ goto fk_end;
+ }
+ nCol = 1;
+ } else if (pToCol != null && pToCol.nExpr != pFromCol.nExpr) {
+ sqlite3ErrorMsg(pParse,
+ "number of columns in foreign key does not match the number of " +
+ "columns in the referenced table");
+ goto fk_end;
+ } else {
+ nCol = pFromCol.nExpr;
+ }
+ //nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey.aCol[0]) + pTo.n + 1;
+ //if( pToCol ){
+ // for(i=0; ia[i].zName) + 1;
+ // }
+ //}
+ pFKey = new FKey();//sqlite3DbMallocZero(db, nByte );
+ if (pFKey == null) {
+ goto fk_end;
+ }
+ pFKey.pFrom = p;
+ pFKey.pNextFrom = p.pFKey;
+ //z = pFKey.aCol[nCol].zCol;
+ pFKey.aCol = new FKey.sColMap[nCol];// z;
+ pFKey.aCol[0] = new FKey.sColMap();
+ pFKey.zTo = pTo.z.Substring(0, pTo.n); //memcpy( z, pTo.z, pTo.n );
+ //z[pTo.n] = 0;
+ sqlite3Dequote(ref pFKey.zTo);
+ //z += pTo.n + 1;
+ pFKey.nCol = nCol;
+ if (pFromCol == null) {
+ pFKey.aCol[0].iFrom = p.nCol - 1;
+ } else {
+ for (i = 0; i < nCol; i++) {
+ if (pFKey.aCol[i] == null)
+ pFKey.aCol[i] = new FKey.sColMap();
+ int j;
+ for (j = 0; j < p.nCol; j++) {
+ if (p.aCol[j].zName.Equals(pFromCol.a[i].zName, StringComparison.OrdinalIgnoreCase)) {
+ pFKey.aCol[i].iFrom = j;
+ break;
+ }
+ }
+ if (j >= p.nCol) {
+ sqlite3ErrorMsg(pParse,
+ "unknown column \"%s\" in foreign key definition",
+ pFromCol.a[i].zName);
+ goto fk_end;
+ }
+ }
+ }
+ if (pToCol != null) {
+ for (i = 0; i < nCol; i++) {
+ ////int n = sqlite3Strlen30( pToCol.a[i].zName );
+ if (pFKey.aCol[i] == null)
+ pFKey.aCol[i] = new FKey.sColMap();
+ pFKey.aCol[i].zCol = pToCol.a[i].zName;
+ //memcpy( z, pToCol.a[i].zName, n );
+ //z[n] = 0;
+ //z += n + 1;
+ }
+ }
+ pFKey.isDeferred = 0;
+ pFKey.aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
+ pFKey.aAction[1] = (u8)((flags >> 8) & 0xff); /* ON UPDATE action */
+
+ Debug.Assert(sqlite3SchemaMutexHeld(db, 0, p.pSchema));
+ pNextTo = sqlite3HashInsert(ref p.pSchema.fkeyHash,
+ pFKey.zTo, sqlite3Strlen30(pFKey.zTo), pFKey
+ );
+ //if( pNextTo==pFKey ){
+ // db.mallocFailed = 1;
+ // goto fk_end;
+ //}
+ if (pNextTo != null) {
+ Debug.Assert(pNextTo.pPrevTo == null);
+ pFKey.pNextTo = pNextTo;
+ pNextTo.pPrevTo = pFKey;
+ }
+ /* Link the foreign key to the table as the last step.
+ */
+ p.pFKey = pFKey;
+ pFKey = null;
-fk_end:
- sqlite3DbFree( db, ref pFKey );
+ fk_end:
+ sqlite3DbFree(db, ref pFKey);
#endif // * !SQLITE_OMIT_FOREIGN_KEY) */
- sqlite3ExprListDelete( db, ref pFromCol );
- sqlite3ExprListDelete( db, ref pToCol );
- }
+ sqlite3ExprListDelete(db, ref pFromCol);
+ sqlite3ExprListDelete(db, ref pToCol);
+ }
- /*
- ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
- ** clause is seen as part of a foreign key definition. The isDeferred
- ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
- ** The behavior of the most recently created foreign key is adjusted
- ** accordingly.
- */
- static void sqlite3DeferForeignKey( Parse pParse, int isDeferred )
- {
+ /*
+ ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
+ ** clause is seen as part of a foreign key definition. The isDeferred
+ ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
+ ** The behavior of the most recently created foreign key is adjusted
+ ** accordingly.
+ */
+ static void sqlite3DeferForeignKey(Parse pParse, int isDeferred) {
#if !SQLITE_OMIT_FOREIGN_KEY
- Table pTab;
- FKey pFKey;
- if ( ( pTab = pParse.pNewTable ) == null || ( pFKey = pTab.pFKey ) == null )
- return;
- Debug.Assert( isDeferred == 0 || isDeferred == 1 ); /* EV: R-30323-21917 */
- pFKey.isDeferred = (u8)isDeferred;
+ Table pTab;
+ FKey pFKey;
+ if ((pTab = pParse.pNewTable) == null || (pFKey = pTab.pFKey) == null)
+ return;
+ Debug.Assert(isDeferred == 0 || isDeferred == 1); /* EV: R-30323-21917 */
+ pFKey.isDeferred = (u8)isDeferred;
#endif
- }
+ }
- /*
- ** Generate code that will erase and refill index pIdx. This is
- ** used to initialize a newly created index or to recompute the
- ** content of an index in response to a REINDEX command.
- **
- ** if memRootPage is not negative, it means that the index is newly
- ** created. The register specified by memRootPage contains the
- ** root page number of the index. If memRootPage is negative, then
- ** the index already exists and must be cleared before being refilled and
- ** the root page number of the index is taken from pIndex.tnum.
- */
- static void sqlite3RefillIndex( Parse pParse, Index pIndex, int memRootPage )
- {
- Table pTab = pIndex.pTable; /* The table that is indexed */
- int iTab = pParse.nTab++; /* Btree cursor used for pTab */
- int iIdx = pParse.nTab++; /* Btree cursor used for pIndex */
- int addr1; /* Address of top of loop */
- int tnum; /* Root page of index */
- Vdbe v; /* Generate code into this virtual machine */
- KeyInfo pKey; /* KeyInfo for index */
- int regIdxKey; /* Registers containing the index key */
- int regRecord; /* Register holding assemblied index record */
- sqlite3 db = pParse.db; /* The database connection */
- int iDb = sqlite3SchemaToIndex( db, pIndex.pSchema );
+ /*
+ ** Generate code that will erase and refill index pIdx. This is
+ ** used to initialize a newly created index or to recompute the
+ ** content of an index in response to a REINDEX command.
+ **
+ ** if memRootPage is not negative, it means that the index is newly
+ ** created. The register specified by memRootPage contains the
+ ** root page number of the index. If memRootPage is negative, then
+ ** the index already exists and must be cleared before being refilled and
+ ** the root page number of the index is taken from pIndex.tnum.
+ */
+ static void sqlite3RefillIndex(Parse pParse, Index pIndex, int memRootPage) {
+ Table pTab = pIndex.pTable; /* The table that is indexed */
+ int iTab = pParse.nTab++; /* Btree cursor used for pTab */
+ int iIdx = pParse.nTab++; /* Btree cursor used for pIndex */
+ int addr1; /* Address of top of loop */
+ int tnum; /* Root page of index */
+ Vdbe v; /* Generate code into this virtual machine */
+ KeyInfo pKey; /* KeyInfo for index */
+ int regIdxKey; /* Registers containing the index key */
+ int regRecord; /* Register holding assemblied index record */
+ sqlite3 db = pParse.db; /* The database connection */
+ int iDb = sqlite3SchemaToIndex(db, pIndex.pSchema);
#if !SQLITE_OMIT_AUTHORIZATION
if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex.zName, 0,
@@ -2738,263 +2505,232 @@ static void sqlite3RefillIndex( Parse pParse, Index pIndex, int memRootPage )
}
#endif
- /* Require a write-lock on the table to perform this operation */
- sqlite3TableLock( pParse, iDb, pTab.tnum, 1, pTab.zName );
- v = sqlite3GetVdbe( pParse );
- if ( v == null )
- return;
- if ( memRootPage >= 0 )
- {
- tnum = memRootPage;
- }
- else
- {
- tnum = pIndex.tnum;
- sqlite3VdbeAddOp2( v, OP_Clear, tnum, iDb );
- }
- pKey = sqlite3IndexKeyinfo( pParse, pIndex );
- sqlite3VdbeAddOp4( v, OP_OpenWrite, iIdx, tnum, iDb,
- pKey, P4_KEYINFO_HANDOFF );
- if ( memRootPage >= 0 )
- {
- sqlite3VdbeChangeP5( v, 1 );
- }
- sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead );
- addr1 = sqlite3VdbeAddOp2( v, OP_Rewind, iTab, 0 );
- regRecord = sqlite3GetTempReg( pParse );
- regIdxKey = sqlite3GenerateIndexKey( pParse, pIndex, iTab, regRecord, true );
- if ( pIndex.onError != OE_None )
- {
- int regRowid = regIdxKey + pIndex.nColumn;
- int j2 = sqlite3VdbeCurrentAddr( v ) + 2;
- int pRegKey = regIdxKey;// SQLITE_INT_TO_PTR( regIdxKey );
-
- /* The registers accessed by the OP_IsUnique opcode were allocated
- ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
- ** call above. Just before that function was freed they were released
- ** (made available to the compiler for reuse) using
- ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
- ** opcode use the values stored within seems dangerous. However, since
- ** we can be sure that no other temp registers have been allocated
- ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
+ /* Require a write-lock on the table to perform this operation */
+ sqlite3TableLock(pParse, iDb, pTab.tnum, 1, pTab.zName);
+ v = sqlite3GetVdbe(pParse);
+ if (v == null)
+ return;
+ if (memRootPage >= 0) {
+ tnum = memRootPage;
+ } else {
+ tnum = pIndex.tnum;
+ sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
+ }
+ pKey = sqlite3IndexKeyinfo(pParse, pIndex);
+ sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
+ pKey, P4_KEYINFO_HANDOFF);
+ if (memRootPage >= 0) {
+ sqlite3VdbeChangeP5(v, 1);
+ }
+ sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
+ addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0);
+ regRecord = sqlite3GetTempReg(pParse);
+ regIdxKey = sqlite3GenerateIndexKey(pParse, pIndex, iTab, regRecord, true);
+ if (pIndex.onError != OE_None) {
+ int regRowid = regIdxKey + pIndex.nColumn;
+ int j2 = sqlite3VdbeCurrentAddr(v) + 2;
+ int pRegKey = regIdxKey;// SQLITE_INT_TO_PTR( regIdxKey );
+
+ /* The registers accessed by the OP_IsUnique opcode were allocated
+ ** using sqlite3GetTempRange() inside of the sqlite3GenerateIndexKey()
+ ** call above. Just before that function was freed they were released
+ ** (made available to the compiler for reuse) using
+ ** sqlite3ReleaseTempRange(). So in some ways having the OP_IsUnique
+ ** opcode use the values stored within seems dangerous. However, since
+ ** we can be sure that no other temp registers have been allocated
+ ** since sqlite3ReleaseTempRange() was called, it is safe to do so.
+ */
+ sqlite3VdbeAddOp4(v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32);
+ sqlite3HaltConstraint(
+ pParse, OE_Abort, "indexed columns are not unique", P4_STATIC);
+ }
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdx, regRecord);
+ sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
+ sqlite3ReleaseTempReg(pParse, regRecord);
+ sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1 + 1);
+ sqlite3VdbeJumpHere(v, addr1);
+ sqlite3VdbeAddOp1(v, OP_Close, iTab);
+ sqlite3VdbeAddOp1(v, OP_Close, iIdx);
+ }
+
+ /*
+ ** Create a new index for an SQL table. pName1.pName2 is the name of the index
+ ** and pTblList is the name of the table that is to be indexed. Both will
+ ** be NULL for a primary key or an index that is created to satisfy a
+ ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse.pNewTable
+ ** as the table to be indexed. pParse.pNewTable is a table that is
+ ** currently being constructed by a CREATE TABLE statement.
+ **
+ ** pList is a list of columns to be indexed. pList will be NULL if this
+ ** is a primary key or unique-constraint on the most recent column added
+ ** to the table currently under construction.
+ **
+ ** If the index is created successfully, return a pointer to the new Index
+ ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
+ ** as the tables primary key (Index.autoIndex==2).
*/
- sqlite3VdbeAddOp4( v, OP_IsUnique, iIdx, j2, regRowid, pRegKey, P4_INT32 );
- sqlite3HaltConstraint(
- pParse, OE_Abort, "indexed columns are not unique", P4_STATIC );
- }
- sqlite3VdbeAddOp2( v, OP_IdxInsert, iIdx, regRecord );
- sqlite3VdbeChangeP5( v, OPFLAG_USESEEKRESULT );
- sqlite3ReleaseTempReg( pParse, regRecord );
- sqlite3VdbeAddOp2( v, OP_Next, iTab, addr1 + 1 );
- sqlite3VdbeJumpHere( v, addr1 );
- sqlite3VdbeAddOp1( v, OP_Close, iTab );
- sqlite3VdbeAddOp1( v, OP_Close, iIdx );
- }
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static Index sqlite3CreateIndex(Parse pParse, int null_2, int null_3, int null_4, int null_5, int onError, int null_7, int null_8, int sortOrder, int ifNotExist) {
+ return sqlite3CreateIndex(pParse, null, null, null, null, onError, null, null, sortOrder, ifNotExist);
+ }
+ static Index sqlite3CreateIndex(Parse pParse, int null_2, int null_3, int null_4, ExprList pList, int onError, int null_7, int null_8, int sortOrder, int ifNotExist) {
+ return sqlite3CreateIndex(pParse, null, null, null, pList, onError, null, null, sortOrder, ifNotExist);
+ }
+ static Index sqlite3CreateIndex(
+ Parse pParse, /* All information about this Parse */
+ Token pName1, /* First part of index name. May be NULL */
+ Token pName2, /* Second part of index name. May be NULL */
+ SrcList pTblName, /* Table to index. Use pParse.pNewTable if 0 */
+ ExprList pList, /* A list of columns to be indexed */
+ int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
+ Token pStart, /* The CREATE token that begins this statement */
+ Token pEnd, /* The ")" that closes the CREATE INDEX statement */
+ int sortOrder, /* Sort order of primary key when pList==NULL */
+ int ifNotExist /* Omit error if index already exists */
+ ) {
+ Index pRet = null; /* Pointer to return */
+ Table pTab = null; /* Table to be indexed */
+ Index pIndex = null; /* The index to be created */
+ string zName = null; /* Name of the index */
+ int nName; /* Number of characters in zName */
+ int i, j;
+ Token nullId = new Token(); /* Fake token for an empty ID list */
+ DbFixer sFix = new DbFixer(); /* For assigning database names to pTable */
+ int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
+ sqlite3 db = pParse.db;
+ Db pDb; /* The specific table containing the indexed database */
+ int iDb; /* Index of the database that is being written */
+ Token pName = null; /* Unqualified name of the index to create */
+ ExprList_item pListItem; /* For looping over pList */
+ int nCol;
+ int nExtra = 0;
+ StringBuilder zExtra = new StringBuilder();
+
+ Debug.Assert(pStart == null || pEnd != null); /* pEnd must be non-NULL if pStart is */
+ Debug.Assert(pParse.nErr == 0); /* Never called with prior errors */
+ if ( /* db.mallocFailed != 0 || */
+ IN_DECLARE_VTAB(pParse)) {
+ goto exit_create_index;
+ }
+ if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
+ goto exit_create_index;
+ }
- /*
- ** Create a new index for an SQL table. pName1.pName2 is the name of the index
- ** and pTblList is the name of the table that is to be indexed. Both will
- ** be NULL for a primary key or an index that is created to satisfy a
- ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse.pNewTable
- ** as the table to be indexed. pParse.pNewTable is a table that is
- ** currently being constructed by a CREATE TABLE statement.
- **
- ** pList is a list of columns to be indexed. pList will be NULL if this
- ** is a primary key or unique-constraint on the most recent column added
- ** to the table currently under construction.
- **
- ** If the index is created successfully, return a pointer to the new Index
- ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
- ** as the tables primary key (Index.autoIndex==2).
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static Index sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, int null_5, int onError, int null_7, int null_8, int sortOrder, int ifNotExist )
- {
- return sqlite3CreateIndex( pParse, null, null, null, null, onError, null, null, sortOrder, ifNotExist );
- }
- static Index sqlite3CreateIndex( Parse pParse, int null_2, int null_3, int null_4, ExprList pList, int onError, int null_7, int null_8, int sortOrder, int ifNotExist )
- {
- return sqlite3CreateIndex( pParse, null, null, null, pList, onError, null, null, sortOrder, ifNotExist );
- }
- static Index sqlite3CreateIndex(
- Parse pParse, /* All information about this Parse */
- Token pName1, /* First part of index name. May be NULL */
- Token pName2, /* Second part of index name. May be NULL */
- SrcList pTblName, /* Table to index. Use pParse.pNewTable if 0 */
- ExprList pList, /* A list of columns to be indexed */
- int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
- Token pStart, /* The CREATE token that begins this statement */
- Token pEnd, /* The ")" that closes the CREATE INDEX statement */
- int sortOrder, /* Sort order of primary key when pList==NULL */
- int ifNotExist /* Omit error if index already exists */
- )
- {
- Index pRet = null; /* Pointer to return */
- Table pTab = null; /* Table to be indexed */
- Index pIndex = null; /* The index to be created */
- string zName = null; /* Name of the index */
- int nName; /* Number of characters in zName */
- int i, j;
- Token nullId = new Token(); /* Fake token for an empty ID list */
- DbFixer sFix = new DbFixer(); /* For assigning database names to pTable */
- int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
- sqlite3 db = pParse.db;
- Db pDb; /* The specific table containing the indexed database */
- int iDb; /* Index of the database that is being written */
- Token pName = null; /* Unqualified name of the index to create */
- ExprList_item pListItem; /* For looping over pList */
- int nCol;
- int nExtra = 0;
- StringBuilder zExtra = new StringBuilder();
-
- Debug.Assert( pStart == null || pEnd != null ); /* pEnd must be non-NULL if pStart is */
- Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */
- if ( /* db.mallocFailed != 0 || */
- IN_DECLARE_VTAB( pParse ) )
- {
- goto exit_create_index;
- }
- if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
- {
- goto exit_create_index;
- }
-
- /*
- ** Find the table that is to be indexed. Return early if not found.
- */
- if ( pTblName != null )
- {
+ /*
+ ** Find the table that is to be indexed. Return early if not found.
+ */
+ if (pTblName != null) {
- /* Use the two-part index name to determine the database
- ** to search for the table. 'Fix' the table name to this db
- ** before looking up the table.
- */
- Debug.Assert( pName1 != null && pName2 != null );
- iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pName );
- if ( iDb < 0 )
- goto exit_create_index;
+ /* Use the two-part index name to determine the database
+ ** to search for the table. 'Fix' the table name to this db
+ ** before looking up the table.
+ */
+ Debug.Assert(pName1 != null && pName2 != null);
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, ref pName);
+ if (iDb < 0)
+ goto exit_create_index;
#if !SQLITE_OMIT_TEMPDB
- /* If the index name was unqualified, check if the the table
-** is a temp table. If so, set the database to 1. Do not do this
-** if initialising a database schema.
-*/
- if ( 0 == db.init.busy )
- {
- pTab = sqlite3SrcListLookup( pParse, pTblName );
- if ( pName2.n == 0 && pTab != null && pTab.pSchema == db.aDb[1].pSchema )
- {
- iDb = 1;
- }
- }
+ /* If the index name was unqualified, check if the the table
+ ** is a temp table. If so, set the database to 1. Do not do this
+ ** if initialising a database schema.
+ */
+ if (0 == db.init.busy) {
+ pTab = sqlite3SrcListLookup(pParse, pTblName);
+ if (pName2.n == 0 && pTab != null && pTab.pSchema == db.aDb[1].pSchema) {
+ iDb = 1;
+ }
+ }
#endif
- if ( sqlite3FixInit( sFix, pParse, iDb, "index", pName ) != 0 &&
- sqlite3FixSrcList( sFix, pTblName ) != 0
- )
- {
- /* Because the parser constructs pTblName from a single identifier,
- ** sqlite3FixSrcList can never fail. */
- Debugger.Break();
- }
- pTab = sqlite3LocateTable( pParse, 0, pTblName.a[0].zName,
- pTblName.a[0].zDatabase );
- if ( pTab == null /*|| db.mallocFailed != 0 */ )
- goto exit_create_index;
- Debug.Assert( db.aDb[iDb].pSchema == pTab.pSchema );
- }
- else
- {
- Debug.Assert( pName == null );
- pTab = pParse.pNewTable;
- if ( pTab == null )
- goto exit_create_index;
- iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
- }
- pDb = db.aDb[iDb];
-
- Debug.Assert( pTab != null );
- Debug.Assert( pParse.nErr == 0 );
-
- if ( pTab.zName.StartsWith( "sqlite_", System.StringComparison.OrdinalIgnoreCase )
- && !pTab.zName.StartsWith( "sqlite_altertab_", System.StringComparison.OrdinalIgnoreCase ) )
- {
- sqlite3ErrorMsg( pParse, "table %s may not be indexed", pTab.zName );
- goto exit_create_index;
- }
+ if (sqlite3FixInit(sFix, pParse, iDb, "index", pName) != 0 &&
+ sqlite3FixSrcList(sFix, pTblName) != 0
+ ) {
+ /* Because the parser constructs pTblName from a single identifier,
+ ** sqlite3FixSrcList can never fail. */
+ Debugger.Break();
+ }
+ pTab = sqlite3LocateTable(pParse, 0, pTblName.a[0].zName,
+ pTblName.a[0].zDatabase);
+ if (pTab == null /*|| db.mallocFailed != 0 */ )
+ goto exit_create_index;
+ Debug.Assert(db.aDb[iDb].pSchema == pTab.pSchema);
+ } else {
+ Debug.Assert(pName == null);
+ pTab = pParse.pNewTable;
+ if (pTab == null)
+ goto exit_create_index;
+ iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
+ }
+ pDb = db.aDb[iDb];
+
+ Debug.Assert(pTab != null);
+ Debug.Assert(pParse.nErr == 0);
+
+ if (pTab.zName.StartsWith("sqlite_", System.StringComparison.OrdinalIgnoreCase)
+ && !pTab.zName.StartsWith("sqlite_altertab_", System.StringComparison.OrdinalIgnoreCase)) {
+ sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab.zName);
+ goto exit_create_index;
+ }
#if !SQLITE_OMIT_VIEW
- if ( pTab.pSelect != null )
- {
- sqlite3ErrorMsg( pParse, "views may not be indexed" );
- goto exit_create_index;
- }
+ if (pTab.pSelect != null) {
+ sqlite3ErrorMsg(pParse, "views may not be indexed");
+ goto exit_create_index;
+ }
#endif
- if ( IsVirtual( pTab ) )
- {
- sqlite3ErrorMsg( pParse, "virtual tables may not be indexed" );
- goto exit_create_index;
- }
-
- /*
- ** Find the name of the index. Make sure there is not already another
- ** index or table with the same name.
- **
- ** Exception: If we are reading the names of permanent indices from the
- ** sqlite_master table (because some other process changed the schema) and
- ** one of the index names collides with the name of a temporary table or
- ** index, then we will continue to process this index.
- **
- ** If pName==0 it means that we are
- ** dealing with a primary key or UNIQUE constraint. We have to invent our
- ** own name.
- */
- if ( pName != null )
- {
- zName = sqlite3NameFromToken( db, pName );
- if ( zName == null )
- goto exit_create_index;
- if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
- {
- goto exit_create_index;
- }
- if ( 0 == db.init.busy )
- {
- if ( sqlite3FindTable( db, zName, null ) != null )
- {
- sqlite3ErrorMsg( pParse, "there is already a table named %s", zName );
- goto exit_create_index;
- }
- }
- if ( sqlite3FindIndex( db, zName, pDb.zName ) != null )
- {
- if ( ifNotExist == 0 )
- {
- sqlite3ErrorMsg( pParse, "index %s already exists", zName );
- }
- else
- {
- Debug.Assert( 0 == db.init.busy );
- sqlite3CodeVerifySchema( pParse, iDb );
- }
- goto exit_create_index;
- }
- }
- else
- {
- int n = 0;
- Index pLoop;
- for ( pLoop = pTab.pIndex, n = 1; pLoop != null; pLoop = pLoop.pNext, n++ )
- {
- }
- zName = sqlite3MPrintf( db, "sqlite_autoindex_%s_%d", pTab.zName, n );
- if ( zName == null )
- {
- goto exit_create_index;
- }
- }
+ if (IsVirtual(pTab)) {
+ sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
+ goto exit_create_index;
+ }
- /* Check for authorization to create an index.
- */
+ /*
+ ** Find the name of the index. Make sure there is not already another
+ ** index or table with the same name.
+ **
+ ** Exception: If we are reading the names of permanent indices from the
+ ** sqlite_master table (because some other process changed the schema) and
+ ** one of the index names collides with the name of a temporary table or
+ ** index, then we will continue to process this index.
+ **
+ ** If pName==0 it means that we are
+ ** dealing with a primary key or UNIQUE constraint. We have to invent our
+ ** own name.
+ */
+ if (pName != null) {
+ zName = sqlite3NameFromToken(db, pName);
+ if (zName == null)
+ goto exit_create_index;
+ if (SQLITE_OK != sqlite3CheckObjectName(pParse, zName)) {
+ goto exit_create_index;
+ }
+ if (0 == db.init.busy) {
+ if (sqlite3FindTable(db, zName, null) != null) {
+ sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
+ goto exit_create_index;
+ }
+ }
+ if (sqlite3FindIndex(db, zName, pDb.zName) != null) {
+ if (ifNotExist == 0) {
+ sqlite3ErrorMsg(pParse, "index %s already exists", zName);
+ } else {
+ Debug.Assert(0 == db.init.busy);
+ sqlite3CodeVerifySchema(pParse, iDb);
+ }
+ goto exit_create_index;
+ }
+ } else {
+ int n = 0;
+ Index pLoop;
+ for (pLoop = pTab.pIndex, n = 1; pLoop != null; pLoop = pLoop.pNext, n++) {
+ }
+ zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab.zName, n);
+ if (zName == null) {
+ goto exit_create_index;
+ }
+ }
+
+ /* Check for authorization to create an index.
+ */
#if !SQLITE_OMIT_AUTHORIZATION
{
string zDb = pDb.zName;
@@ -3009,445 +2745,399 @@ static Index sqlite3CreateIndex(
}
#endif
- /* If pList==0, it means this routine was called to make a primary
-** key out of the last column added to the table under construction.
-** So create a fake list to simulate this.
-*/
- if ( pList == null )
- {
- nullId.z = pTab.aCol[pTab.nCol - 1].zName;
- nullId.n = sqlite3Strlen30( nullId.z );
- pList = sqlite3ExprListAppend( pParse, null, null );
- if ( pList == null )
- goto exit_create_index;
- sqlite3ExprListSetName( pParse, pList, nullId, 0 );
- pList.a[0].sortOrder = (u8)sortOrder;
- }
-
- /* Figure out how many bytes of space are required to store explicitly
- ** specified collation sequence names.
+ /* If pList==0, it means this routine was called to make a primary
+ ** key out of the last column added to the table under construction.
+ ** So create a fake list to simulate this.
*/
- for ( i = 0; i < pList.nExpr; i++ )
- {
- Expr pExpr = pList.a[i].pExpr;
- if ( pExpr != null )
- {
- CollSeq pColl = pExpr.pColl;
- /* Either pColl!=0 or there was an OOM failure. But if an OOM
- ** failure we have quit before reaching this point. */
- if ( ALWAYS( pColl != null ) )
- {
- nExtra += ( 1 + sqlite3Strlen30( pColl.zName ) );
- }
- }
- }
+ if (pList == null) {
+ nullId.z = pTab.aCol[pTab.nCol - 1].zName;
+ nullId.n = sqlite3Strlen30(nullId.z);
+ pList = sqlite3ExprListAppend(pParse, null, null);
+ if (pList == null)
+ goto exit_create_index;
+ sqlite3ExprListSetName(pParse, pList, nullId, 0);
+ pList.a[0].sortOrder = (u8)sortOrder;
+ }
- /*
- ** Allocate the index structure.
- */
- nName = sqlite3Strlen30( zName );
- nCol = pList.nExpr;
- pIndex = new Index();
- // sqlite3DbMallocZero( db,
- // Index.Length + /* Index structure */
- // sizeof( int ) * nCol + /* Index.aiColumn */
- // sizeof( int ) * ( nCol + 1 ) + /* Index.aiRowEst */
- // sizeof( char* ) * nCol + /* Index.azColl */
- // u8.Length * nCol + /* Index.aSortOrder */
- // nName + 1 + /* Index.zName */
- // nExtra /* Collation sequence names */
- //);
- //if ( db.mallocFailed != 0 )
- //{
- // goto exit_create_index;
- //}
- pIndex.azColl = new string[nCol + 1];//(char*)(pIndex[1]);
- pIndex.aiColumn = new int[nCol + 1];//(int )(pIndex->azColl[nCol]);
- pIndex.aiRowEst = new int[nCol + 1];//(unsigned )(pIndex->aiColumn[nCol]);
- pIndex.aSortOrder = new byte[nCol + 1];//(u8 )(pIndex->aiRowEst[nCol+1]);
- //pIndex.zName = null;// (char)( &pIndex->aSortOrder[nCol] );
- zExtra = new StringBuilder( nName + 1 );// (char)( &pIndex.zName[nName + 1] );
- if ( zName.Length == nName )
- pIndex.zName = zName;
- else
- {
- pIndex.zName = zName.Substring( 0, nName );
- }// memcpy( pIndex.zName, zName, nName + 1 );
- pIndex.pTable = pTab;
- pIndex.nColumn = pList.nExpr;
- pIndex.onError = (u8)onError;
- pIndex.autoIndex = (u8)( pName == null ? 1 : 0 );
- pIndex.pSchema = db.aDb[iDb].pSchema;
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
-
- /* Check to see if we should honor DESC requests on index columns
- */
- if ( pDb.pSchema.file_format >= 4 )
- {
- sortOrderMask = 1; /* Honor DESC */
- }
- else
- {
- sortOrderMask = 0; /* Ignore DESC */
- }
-
- /* Scan the names of the columns of the table to be indexed and
- ** load the column indices into the Index structure. Report an error
- ** if any column is not found.
- **
- ** TODO: Add a test to make sure that the same column is not named
- ** more than once within the same index. Only the first instance of
- ** the column will ever be used by the optimizer. Note that using the
- ** same column more than once cannot be an error because that would
- ** break backwards compatibility - it needs to be a warning.
- */
- for ( i = 0; i < pList.nExpr; i++ )
- {//, pListItem++){
- pListItem = pList.a[i];
- string zColName = pListItem.zName;
- Column pTabCol;
- byte requestedSortOrder;
- string zColl; /* Collation sequence name */
-
- for ( j = 0; j < pTab.nCol; j++ )
- {//, pTabCol++){
- pTabCol = pTab.aCol[j];
- if ( zColName.Equals( pTabCol.zName, StringComparison.OrdinalIgnoreCase ) )
- break;
- }
- if ( j >= pTab.nCol )
- {
- sqlite3ErrorMsg( pParse, "table %s has no column named %s",
- pTab.zName, zColName );
- pParse.checkSchema = 1;
- goto exit_create_index;
- }
- pIndex.aiColumn[i] = j;
- /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
- ** the way the "idxlist" non-terminal is constructed by the parser,
- ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
- ** must exist or else there must have been an OOM error. But if there
- ** was an OOM error, we would never reach this point. */
- if ( pListItem.pExpr != null && ALWAYS( pListItem.pExpr.pColl ) )
- {
- int nColl;
- zColl = pListItem.pExpr.pColl.zName;
- nColl = sqlite3Strlen30( zColl );
- Debug.Assert( nExtra >= nColl );
- zExtra = new StringBuilder( zColl.Substring( 0, nColl ) );// memcpy( zExtra, zColl, nColl );
- zColl = zExtra.ToString();
- //zExtra += nColl;
- nExtra -= nColl;
- }
- else
- {
- zColl = pTab.aCol[j].zColl;
- if ( zColl == null )
- {
- zColl = db.pDfltColl.zName;
- }
- }
- if ( 0 == db.init.busy && sqlite3LocateCollSeq( pParse, zColl ) == null )
- {
- goto exit_create_index;
- }
- pIndex.azColl[i] = zColl;
- requestedSortOrder = (u8)( ( pListItem.sortOrder & sortOrderMask ) != 0 ? 1 : 0 );
- pIndex.aSortOrder[i] = (u8)requestedSortOrder;
- }
- sqlite3DefaultRowEst( pIndex );
-
- if ( pTab == pParse.pNewTable )
- {
- /* This routine has been called to create an automatic index as a
- ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
- ** a PRIMARY KEY or UNIQUE clause following the column definitions.
- ** i.e. one of:
- **
- ** CREATE TABLE t(x PRIMARY KEY, y);
- ** CREATE TABLE t(x, y, UNIQUE(x, y));
- **
- ** Either way, check to see if the table already has such an index. If
- ** so, don't bother creating this one. This only applies to
- ** automatically created indices. Users can do as they wish with
- ** explicit indices.
- **
- ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
- ** (and thus suppressing the second one) even if they have different
- ** sort orders.
- **
- ** If there are different collating sequences or if the columns of
- ** the constraint occur in different orders, then the constraints are
- ** considered distinct and both result in separate indices.
- */
- Index pIdx;
- for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- int k;
- Debug.Assert( pIdx.onError != OE_None );
- Debug.Assert( pIdx.autoIndex != 0 );
- Debug.Assert( pIndex.onError != OE_None );
-
- if ( pIdx.nColumn != pIndex.nColumn )
- continue;
- for ( k = 0; k < pIdx.nColumn; k++ )
- {
- string z1;
- string z2;
- if ( pIdx.aiColumn[k] != pIndex.aiColumn[k] )
- break;
- z1 = pIdx.azColl[k];
- z2 = pIndex.azColl[k];
- if ( z1 != z2 && !z1.Equals( z2, StringComparison.OrdinalIgnoreCase ) )
- break;
- }
- if ( k == pIdx.nColumn )
- {
- if ( pIdx.onError != pIndex.onError )
- {
- /* This constraint creates the same index as a previous
- ** constraint specified somewhere in the CREATE TABLE statement.
- ** However the ON CONFLICT clauses are different. If both this
- ** constraint and the previous equivalent constraint have explicit
- ** ON CONFLICT clauses this is an error. Otherwise, use the
- ** explicitly specified behavior for the index.
- */
- if ( !( pIdx.onError == OE_Default || pIndex.onError == OE_Default ) )
- {
- sqlite3ErrorMsg( pParse,
- "conflicting ON CONFLICT clauses specified", 0 );
- }
- if ( pIdx.onError == OE_Default )
- {
- pIdx.onError = pIndex.onError;
- }
+ /* Figure out how many bytes of space are required to store explicitly
+ ** specified collation sequence names.
+ */
+ for (i = 0; i < pList.nExpr; i++) {
+ Expr pExpr = pList.a[i].pExpr;
+ if (pExpr != null) {
+ CollSeq pColl = pExpr.pColl;
+ /* Either pColl!=0 or there was an OOM failure. But if an OOM
+ ** failure we have quit before reaching this point. */
+ if (ALWAYS(pColl != null)) {
+ nExtra += (1 + sqlite3Strlen30(pColl.zName));
+ }
+ }
}
- goto exit_create_index;
- }
- }
- }
- /* Link the new Index structure to its table and to the other
- ** in-memory database structures.
- */
- if ( db.init.busy != 0 )
- {
- Index p;
- Debug.Assert( sqlite3SchemaMutexHeld( db, 0, pIndex.pSchema ) );
- p = sqlite3HashInsert( ref pIndex.pSchema.idxHash,
- pIndex.zName, sqlite3Strlen30( pIndex.zName ),
- pIndex );
- if ( p != null )
- {
- Debug.Assert( p == pIndex ); /* Malloc must have failed */
- // db.mallocFailed = 1;
- goto exit_create_index;
- }
- db.flags |= SQLITE_InternChanges;
- if ( pTblName != null )
- {
- pIndex.tnum = db.init.newTnum;
- }
- }
-
- /* If the db.init.busy is 0 then create the index on disk. This
- ** involves writing the index into the master table and filling in the
- ** index with the current table contents.
- **
- ** The db.init.busy is 0 when the user first enters a CREATE INDEX
- ** command. db.init.busy is 1 when a database is opened and
- ** CREATE INDEX statements are read out of the master table. In
- ** the latter case the index already exists on disk, which is why
- ** we don't want to recreate it.
- **
- ** If pTblName==0 it means this index is generated as a primary key
- ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
- ** has just been created, it contains no data and the index initialization
- ** step can be skipped.
- */
- else //if ( 0 == db.init.busy )
- {
- Vdbe v;
- string zStmt;
- int iMem = ++pParse.nMem;
+ /*
+ ** Allocate the index structure.
+ */
+ nName = sqlite3Strlen30(zName);
+ nCol = pList.nExpr;
+ pIndex = new Index();
+ // sqlite3DbMallocZero( db,
+ // Index.Length + /* Index structure */
+ // sizeof( int ) * nCol + /* Index.aiColumn */
+ // sizeof( int ) * ( nCol + 1 ) + /* Index.aiRowEst */
+ // sizeof( char* ) * nCol + /* Index.azColl */
+ // u8.Length * nCol + /* Index.aSortOrder */
+ // nName + 1 + /* Index.zName */
+ // nExtra /* Collation sequence names */
+ //);
+ //if ( db.mallocFailed != 0 )
+ //{
+ // goto exit_create_index;
+ //}
+ pIndex.azColl = new string[nCol + 1];//(char*)(pIndex[1]);
+ pIndex.aiColumn = new int[nCol + 1];//(int )(pIndex->azColl[nCol]);
+ pIndex.aiRowEst = new int[nCol + 1];//(unsigned )(pIndex->aiColumn[nCol]);
+ pIndex.aSortOrder = new byte[nCol + 1];//(u8 )(pIndex->aiRowEst[nCol+1]);
+ //pIndex.zName = null;// (char)( &pIndex->aSortOrder[nCol] );
+ zExtra = new StringBuilder(nName + 1);// (char)( &pIndex.zName[nName + 1] );
+ if (zName.Length == nName)
+ pIndex.zName = zName;
+ else {
+ pIndex.zName = zName.Substring(0, nName);
+ }// memcpy( pIndex.zName, zName, nName + 1 );
+ pIndex.pTable = pTab;
+ pIndex.nColumn = pList.nExpr;
+ pIndex.onError = (u8)onError;
+ pIndex.autoIndex = (u8)(pName == null ? 1 : 0);
+ pIndex.pSchema = db.aDb[iDb].pSchema;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+
+ /* Check to see if we should honor DESC requests on index columns
+ */
+ if (pDb.pSchema.file_format >= 4) {
+ sortOrderMask = 1; /* Honor DESC */
+ } else {
+ sortOrderMask = 0; /* Ignore DESC */
+ }
- v = sqlite3GetVdbe( pParse );
- if ( v == null )
- goto exit_create_index;
+ /* Scan the names of the columns of the table to be indexed and
+ ** load the column indices into the Index structure. Report an error
+ ** if any column is not found.
+ **
+ ** TODO: Add a test to make sure that the same column is not named
+ ** more than once within the same index. Only the first instance of
+ ** the column will ever be used by the optimizer. Note that using the
+ ** same column more than once cannot be an error because that would
+ ** break backwards compatibility - it needs to be a warning.
+ */
+ for (i = 0; i < pList.nExpr; i++) {//, pListItem++){
+ pListItem = pList.a[i];
+ string zColName = pListItem.zName;
+ Column pTabCol;
+ byte requestedSortOrder;
+ string zColl; /* Collation sequence name */
+
+ for (j = 0; j < pTab.nCol; j++) {//, pTabCol++){
+ pTabCol = pTab.aCol[j];
+ if (zColName.Equals(pTabCol.zName, StringComparison.OrdinalIgnoreCase))
+ break;
+ }
+ if (j >= pTab.nCol) {
+ sqlite3ErrorMsg(pParse, "table %s has no column named %s",
+ pTab.zName, zColName);
+ pParse.checkSchema = 1;
+ goto exit_create_index;
+ }
+ pIndex.aiColumn[i] = j;
+ /* Justification of the ALWAYS(pListItem->pExpr->pColl): Because of
+ ** the way the "idxlist" non-terminal is constructed by the parser,
+ ** if pListItem->pExpr is not null then either pListItem->pExpr->pColl
+ ** must exist or else there must have been an OOM error. But if there
+ ** was an OOM error, we would never reach this point. */
+ if (pListItem.pExpr != null && ALWAYS(pListItem.pExpr.pColl)) {
+ int nColl;
+ zColl = pListItem.pExpr.pColl.zName;
+ nColl = sqlite3Strlen30(zColl);
+ Debug.Assert(nExtra >= nColl);
+ zExtra = new StringBuilder(zColl.Substring(0, nColl));// memcpy( zExtra, zColl, nColl );
+ zColl = zExtra.ToString();
+ //zExtra += nColl;
+ nExtra -= nColl;
+ } else {
+ zColl = pTab.aCol[j].zColl;
+ if (zColl == null) {
+ zColl = db.pDfltColl.zName;
+ }
+ }
+ if (0 == db.init.busy && sqlite3LocateCollSeq(pParse, zColl) == null) {
+ goto exit_create_index;
+ }
+ pIndex.azColl[i] = zColl;
+ requestedSortOrder = (u8)((pListItem.sortOrder & sortOrderMask) != 0 ? 1 : 0);
+ pIndex.aSortOrder[i] = (u8)requestedSortOrder;
+ }
+ sqlite3DefaultRowEst(pIndex);
+
+ if (pTab == pParse.pNewTable) {
+ /* This routine has been called to create an automatic index as a
+ ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
+ ** a PRIMARY KEY or UNIQUE clause following the column definitions.
+ ** i.e. one of:
+ **
+ ** CREATE TABLE t(x PRIMARY KEY, y);
+ ** CREATE TABLE t(x, y, UNIQUE(x, y));
+ **
+ ** Either way, check to see if the table already has such an index. If
+ ** so, don't bother creating this one. This only applies to
+ ** automatically created indices. Users can do as they wish with
+ ** explicit indices.
+ **
+ ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
+ ** (and thus suppressing the second one) even if they have different
+ ** sort orders.
+ **
+ ** If there are different collating sequences or if the columns of
+ ** the constraint occur in different orders, then the constraints are
+ ** considered distinct and both result in separate indices.
+ */
+ Index pIdx;
+ for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ int k;
+ Debug.Assert(pIdx.onError != OE_None);
+ Debug.Assert(pIdx.autoIndex != 0);
+ Debug.Assert(pIndex.onError != OE_None);
+
+ if (pIdx.nColumn != pIndex.nColumn)
+ continue;
+ for (k = 0; k < pIdx.nColumn; k++) {
+ string z1;
+ string z2;
+ if (pIdx.aiColumn[k] != pIndex.aiColumn[k])
+ break;
+ z1 = pIdx.azColl[k];
+ z2 = pIndex.azColl[k];
+ if (z1 != z2 && !z1.Equals(z2, StringComparison.OrdinalIgnoreCase))
+ break;
+ }
+ if (k == pIdx.nColumn) {
+ if (pIdx.onError != pIndex.onError) {
+ /* This constraint creates the same index as a previous
+ ** constraint specified somewhere in the CREATE TABLE statement.
+ ** However the ON CONFLICT clauses are different. If both this
+ ** constraint and the previous equivalent constraint have explicit
+ ** ON CONFLICT clauses this is an error. Otherwise, use the
+ ** explicitly specified behavior for the index.
+ */
+ if (!(pIdx.onError == OE_Default || pIndex.onError == OE_Default)) {
+ sqlite3ErrorMsg(pParse,
+ "conflicting ON CONFLICT clauses specified", 0);
+ }
+ if (pIdx.onError == OE_Default) {
+ pIdx.onError = pIndex.onError;
+ }
+ }
+ goto exit_create_index;
+ }
+ }
+ }
+ /* Link the new Index structure to its table and to the other
+ ** in-memory database structures.
+ */
+ if (db.init.busy != 0) {
+ Index p;
+ Debug.Assert(sqlite3SchemaMutexHeld(db, 0, pIndex.pSchema));
+ p = sqlite3HashInsert(ref pIndex.pSchema.idxHash,
+ pIndex.zName, sqlite3Strlen30(pIndex.zName),
+ pIndex);
+ if (p != null) {
+ Debug.Assert(p == pIndex); /* Malloc must have failed */
+ // db.mallocFailed = 1;
+ goto exit_create_index;
+ }
+ db.flags |= SQLITE_InternChanges;
+ if (pTblName != null) {
+ pIndex.tnum = db.init.newTnum;
+ }
+ }
- /* Create the rootpage for the index
- */
- sqlite3BeginWriteOperation( pParse, 1, iDb );
- sqlite3VdbeAddOp2( v, OP_CreateIndex, iDb, iMem );
+ /* If the db.init.busy is 0 then create the index on disk. This
+ ** involves writing the index into the master table and filling in the
+ ** index with the current table contents.
+ **
+ ** The db.init.busy is 0 when the user first enters a CREATE INDEX
+ ** command. db.init.busy is 1 when a database is opened and
+ ** CREATE INDEX statements are read out of the master table. In
+ ** the latter case the index already exists on disk, which is why
+ ** we don't want to recreate it.
+ **
+ ** If pTblName==0 it means this index is generated as a primary key
+ ** or UNIQUE constraint of a CREATE TABLE statement. Since the table
+ ** has just been created, it contains no data and the index initialization
+ ** step can be skipped.
+ */
+ else //if ( 0 == db.init.busy )
+ {
+ Vdbe v;
+ string zStmt;
+ int iMem = ++pParse.nMem;
+
+ v = sqlite3GetVdbe(pParse);
+ if (v == null)
+ goto exit_create_index;
+
+
+ /* Create the rootpage for the index
+ */
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+ sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
+
+ /* Gather the complete text of the CREATE INDEX statement into
+ ** the zStmt variable
+ */
+ if (pStart != null) {
+ Debug.Assert(pEnd != null);
+ /* A named index with an explicit CREATE INDEX statement */
+ zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
+ onError == OE_None ? "" : " UNIQUE",
+ (int)(pName.z.Length - pEnd.z.Length) + 1,
+ pName.z);
+ } else {
+ /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
+ /* zStmt = sqlite3MPrintf(""); */
+ zStmt = null;
+ }
+
+ /* Add an entry in sqlite_master for this index
+ */
+ sqlite3NestedParse(pParse,
+ "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
+ db.aDb[iDb].zName, SCHEMA_TABLE(iDb),
+ pIndex.zName,
+ pTab.zName,
+ iMem,
+ zStmt
+ );
+ sqlite3DbFree(db, ref zStmt);
+
+ /* Fill the index with data and reparse the schema. Code an OP_Expire
+ ** to invalidate all pre-compiled statements.
+ */
+ if (pTblName != null) {
+ sqlite3RefillIndex(pParse, pIndex, iMem);
+ sqlite3ChangeCookie(pParse, iDb);
+ sqlite3VdbeAddParseSchemaOp(v, iDb,
+ sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex.zName));
+ sqlite3VdbeAddOp1(v, OP_Expire, 0);
+ }
+ }
- /* Gather the complete text of the CREATE INDEX statement into
- ** the zStmt variable
- */
- if ( pStart != null )
- {
- Debug.Assert( pEnd != null );
- /* A named index with an explicit CREATE INDEX statement */
- zStmt = sqlite3MPrintf( db, "CREATE%s INDEX %.*s",
- onError == OE_None ? "" : " UNIQUE",
- (int)(pName.z.Length - pEnd.z.Length) + 1,
- pName.z );
- }
- else
- {
- /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
- /* zStmt = sqlite3MPrintf(""); */
- zStmt = null;
- }
+ /* When adding an index to the list of indices for a table, make
+ ** sure all indices labeled OE_Replace come after all those labeled
+ ** OE_Ignore. This is necessary for the correct constraint check
+ ** processing (in sqlite3GenerateConstraintChecks()) as part of
+ ** UPDATE and INSERT statements.
+ */
+ if (db.init.busy != 0 || pTblName == null) {
+ if (onError != OE_Replace || pTab.pIndex == null
+ || pTab.pIndex.onError == OE_Replace) {
+ pIndex.pNext = pTab.pIndex;
+ pTab.pIndex = pIndex;
+ } else {
+ Index pOther = pTab.pIndex;
+ while (pOther.pNext != null && pOther.pNext.onError != OE_Replace) {
+ pOther = pOther.pNext;
+ }
+ pIndex.pNext = pOther.pNext;
+ pOther.pNext = pIndex;
+ }
+ pRet = pIndex;
+ pIndex = null;
+ }
- /* Add an entry in sqlite_master for this index
- */
- sqlite3NestedParse( pParse,
- "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
- db.aDb[iDb].zName, SCHEMA_TABLE( iDb ),
- pIndex.zName,
- pTab.zName,
- iMem,
- zStmt
- );
- sqlite3DbFree( db, ref zStmt );
-
- /* Fill the index with data and reparse the schema. Code an OP_Expire
- ** to invalidate all pre-compiled statements.
- */
- if ( pTblName != null )
- {
- sqlite3RefillIndex( pParse, pIndex, iMem );
- sqlite3ChangeCookie( pParse, iDb );
- sqlite3VdbeAddParseSchemaOp( v, iDb,
- sqlite3MPrintf( db, "name='%q' AND type='index'", pIndex.zName ) );
- sqlite3VdbeAddOp1( v, OP_Expire, 0 );
+ /* Clean up before exiting */
+ exit_create_index:
+ if (pIndex != null) {
+ //sqlite3DbFree(db, ref pIndex.zColAff );
+ sqlite3DbFree(db, ref pIndex);
+ }
+ sqlite3ExprListDelete(db, ref pList);
+ sqlite3SrcListDelete(db, ref pTblName);
+ sqlite3DbFree(db, ref zName);
+ return pRet;
}
- }
- /* When adding an index to the list of indices for a table, make
- ** sure all indices labeled OE_Replace come after all those labeled
- ** OE_Ignore. This is necessary for the correct constraint check
- ** processing (in sqlite3GenerateConstraintChecks()) as part of
- ** UPDATE and INSERT statements.
- */
- if ( db.init.busy != 0 || pTblName == null )
- {
- if ( onError != OE_Replace || pTab.pIndex == null
- || pTab.pIndex.onError == OE_Replace )
- {
- pIndex.pNext = pTab.pIndex;
- pTab.pIndex = pIndex;
- }
- else
- {
- Index pOther = pTab.pIndex;
- while ( pOther.pNext != null && pOther.pNext.onError != OE_Replace )
- {
- pOther = pOther.pNext;
- }
- pIndex.pNext = pOther.pNext;
- pOther.pNext = pIndex;
+ /*
+ ** Fill the Index.aiRowEst[] array with default information - information
+ ** to be used when we have not run the ANALYZE command.
+ **
+ ** aiRowEst[0] is suppose to contain the number of elements in the index.
+ ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
+ ** number of rows in the table that match any particular value of the
+ ** first column of the index. aiRowEst[2] is an estimate of the number
+ ** of rows that match any particular combiniation of the first 2 columns
+ ** of the index. And so forth. It must always be the case that
+ *
+ ** aiRowEst[N]<=aiRowEst[N-1]
+ ** aiRowEst[N]>=1
+ **
+ ** Apart from that, we have little to go on besides intuition as to
+ ** how aiRowEst[] should be initialized. The numbers generated here
+ ** are based on typical values found in actual indices.
+ */
+ static void sqlite3DefaultRowEst(Index pIdx) {
+ int[] a = pIdx.aiRowEst;
+ int i;
+ int n;
+ Debug.Assert(a != null);
+ a[0] = (int)pIdx.pTable.nRowEst;
+ if (a[0] < 10)
+ a[0] = 10;
+ n = 10;
+ for (i = 1; i <= pIdx.nColumn; i++) {
+ a[i] = n;
+ if (n > 5)
+ n--;
+ }
+ if (pIdx.onError != OE_None) {
+ a[pIdx.nColumn] = 1;
+ }
}
- pRet = pIndex;
- pIndex = null;
- }
- /* Clean up before exiting */
-exit_create_index:
- if ( pIndex != null )
- {
- //sqlite3DbFree(db, ref pIndex.zColAff );
- sqlite3DbFree( db, ref pIndex );
- }
- sqlite3ExprListDelete( db, ref pList );
- sqlite3SrcListDelete( db, ref pTblName );
- sqlite3DbFree( db, ref zName );
- return pRet;
- }
-
- /*
- ** Fill the Index.aiRowEst[] array with default information - information
- ** to be used when we have not run the ANALYZE command.
- **
- ** aiRowEst[0] is suppose to contain the number of elements in the index.
- ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
- ** number of rows in the table that match any particular value of the
- ** first column of the index. aiRowEst[2] is an estimate of the number
- ** of rows that match any particular combiniation of the first 2 columns
- ** of the index. And so forth. It must always be the case that
- *
- ** aiRowEst[N]<=aiRowEst[N-1]
- ** aiRowEst[N]>=1
- **
- ** Apart from that, we have little to go on besides intuition as to
- ** how aiRowEst[] should be initialized. The numbers generated here
- ** are based on typical values found in actual indices.
- */
- static void sqlite3DefaultRowEst( Index pIdx )
- {
- int[] a = pIdx.aiRowEst;
- int i;
- int n;
- Debug.Assert( a != null );
- a[0] = (int)pIdx.pTable.nRowEst;
- if ( a[0] < 10 )
- a[0] = 10;
- n = 10;
- for ( i = 1; i <= pIdx.nColumn; i++ )
- {
- a[i] = n;
- if ( n > 5 )
- n--;
- }
- if ( pIdx.onError != OE_None )
- {
- a[pIdx.nColumn] = 1;
- }
- }
-
- /*
- ** This routine will drop an existing named index. This routine
- ** implements the DROP INDEX statement.
- */
- static void sqlite3DropIndex( Parse pParse, SrcList pName, int ifExists )
- {
- Index pIndex;
- Vdbe v;
- sqlite3 db = pParse.db;
- int iDb;
-
- Debug.Assert( pParse.nErr == 0 ); /* Never called with prior errors */
- //if ( db.mallocFailed != 0 )
- //{
- // goto exit_drop_index;
- //}
- Debug.Assert( pName.nSrc == 1 );
- if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
- {
- goto exit_drop_index;
- }
- pIndex = sqlite3FindIndex( db, pName.a[0].zName, pName.a[0].zDatabase );
- if ( pIndex == null )
- {
- if ( ifExists == 0 )
- {
- sqlite3ErrorMsg( pParse, "no such index: %S", pName, 0 );
- }
- else
- {
- sqlite3CodeVerifyNamedSchema( pParse, pName.a[0].zDatabase );
- }
- pParse.checkSchema = 1;
- goto exit_drop_index;
- }
- if ( pIndex.autoIndex != 0 )
- {
- sqlite3ErrorMsg( pParse, "index associated with UNIQUE " +
- "or PRIMARY KEY constraint cannot be dropped", 0 );
- goto exit_drop_index;
- }
- iDb = sqlite3SchemaToIndex( db, pIndex.pSchema );
+ /*
+ ** This routine will drop an existing named index. This routine
+ ** implements the DROP INDEX statement.
+ */
+ static void sqlite3DropIndex(Parse pParse, SrcList pName, int ifExists) {
+ Index pIndex;
+ Vdbe v;
+ sqlite3 db = pParse.db;
+ int iDb;
+
+ Debug.Assert(pParse.nErr == 0); /* Never called with prior errors */
+ //if ( db.mallocFailed != 0 )
+ //{
+ // goto exit_drop_index;
+ //}
+ Debug.Assert(pName.nSrc == 1);
+ if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
+ goto exit_drop_index;
+ }
+ pIndex = sqlite3FindIndex(db, pName.a[0].zName, pName.a[0].zDatabase);
+ if (pIndex == null) {
+ if (ifExists == 0) {
+ sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
+ } else {
+ sqlite3CodeVerifyNamedSchema(pParse, pName.a[0].zDatabase);
+ }
+ pParse.checkSchema = 1;
+ goto exit_drop_index;
+ }
+ if (pIndex.autoIndex != 0) {
+ sqlite3ErrorMsg(pParse, "index associated with UNIQUE " +
+ "or PRIMARY KEY constraint cannot be dropped", 0);
+ goto exit_drop_index;
+ }
+ iDb = sqlite3SchemaToIndex(db, pIndex.pSchema);
#if !SQLITE_OMIT_AUTHORIZATION
{
int code = SQLITE_DROP_INDEX;
@@ -3464,959 +3154,866 @@ static void sqlite3DropIndex( Parse pParse, SrcList pName, int ifExists )
}
#endif
- /* Generate code to remove the index and from the master table */
- v = sqlite3GetVdbe( pParse );
- if ( v != null )
- {
- sqlite3BeginWriteOperation( pParse, 1, iDb );
- sqlite3NestedParse( pParse,
- "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
- db.aDb[iDb].zName, SCHEMA_TABLE( iDb ),
- pIndex.zName
- );
- if ( sqlite3FindTable( db, "sqlite_stat1", db.aDb[iDb].zName ) != null )
- {
- sqlite3NestedParse( pParse,
- "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
- db.aDb[iDb].zName, pIndex.zName
- );
+ /* Generate code to remove the index and from the master table */
+ v = sqlite3GetVdbe(pParse);
+ if (v != null) {
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
+ db.aDb[iDb].zName, SCHEMA_TABLE(iDb),
+ pIndex.zName
+ );
+ if (sqlite3FindTable(db, "sqlite_stat1", db.aDb[iDb].zName) != null) {
+ sqlite3NestedParse(pParse,
+ "DELETE FROM %Q.sqlite_stat1 WHERE idx=%Q",
+ db.aDb[iDb].zName, pIndex.zName
+ );
+ }
+ sqlite3ChangeCookie(pParse, iDb);
+ destroyRootPage(pParse, pIndex.tnum, iDb);
+ sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex.zName, 0);
+ }
+
+ exit_drop_index:
+ sqlite3SrcListDelete(db, ref pName);
}
- sqlite3ChangeCookie( pParse, iDb );
- destroyRootPage( pParse, pIndex.tnum, iDb );
- sqlite3VdbeAddOp4( v, OP_DropIndex, iDb, 0, 0, pIndex.zName, 0 );
- }
-exit_drop_index:
- sqlite3SrcListDelete( db, ref pName );
- }
+ /*
+ ** pArray is a pointer to an array of objects. Each object in the
+ ** array is szEntry bytes in size. This routine allocates a new
+ ** object on the end of the array.
+ **
+ ** pnEntry is the number of entries already in use. pnAlloc is
+ ** the previously allocated size of the array. initSize is the
+ ** suggested initial array size allocation.
+ **
+ ** The index of the new entry is returned in pIdx.
+ **
+ ** This routine returns a pointer to the array of objects. This
+ ** might be the same as the pArray parameter or it might be a different
+ ** pointer if the array was resized.
+ */
+ static T[] sqlite3ArrayAllocate(
+ sqlite3 db, /* Connection to notify of malloc failures */
+ T[] pArray, /* Array of objects. Might be reallocated */
+ int szEntry, /* Size of each object in the array */
+ int initSize, /* Suggested initial allocation, in elements */
+ ref int pnEntry, /* Number of objects currently in use */
+ ref int pnAlloc, /* Current size of the allocation, in elements */
+ ref int pIdx /* Write the index of a new slot here */
+ ) where T : new() {
+ //char* z;
+ if (pnEntry >= pnAlloc) {
+ //void* pNew;
+ int newSize;
+ newSize = (pnAlloc) * 2 + initSize;
+ //pNew = sqlite3DbRealloc(db, pArray, newSize * szEntry);
+ //if (pNew == 0)
+ //{
+ // pIdx = -1;
+ // return pArray;
+ //}
+ pnAlloc = newSize; //sqlite3DbMallocSize(db, pNew)/szEntry;
+ //pArray = pNew;
+ Array.Resize(ref pArray, newSize);
+ }
+ pArray[pnEntry] = new T();
+ //z = (char)pArray;
+ //memset(z[*pnEntry * szEntry], 0, szEntry);
+ pIdx = pnEntry;
+ ++pnEntry;
+ return pArray;
+ }
- /*
- ** pArray is a pointer to an array of objects. Each object in the
- ** array is szEntry bytes in size. This routine allocates a new
- ** object on the end of the array.
- **
- ** pnEntry is the number of entries already in use. pnAlloc is
- ** the previously allocated size of the array. initSize is the
- ** suggested initial array size allocation.
- **
- ** The index of the new entry is returned in pIdx.
- **
- ** This routine returns a pointer to the array of objects. This
- ** might be the same as the pArray parameter or it might be a different
- ** pointer if the array was resized.
- */
- static T[] sqlite3ArrayAllocate(
- sqlite3 db, /* Connection to notify of malloc failures */
- T[] pArray, /* Array of objects. Might be reallocated */
- int szEntry, /* Size of each object in the array */
- int initSize, /* Suggested initial allocation, in elements */
- ref int pnEntry, /* Number of objects currently in use */
- ref int pnAlloc, /* Current size of the allocation, in elements */
- ref int pIdx /* Write the index of a new slot here */
- ) where T : new()
- {
- //char* z;
- if ( pnEntry >= pnAlloc )
- {
- //void* pNew;
- int newSize;
- newSize = ( pnAlloc ) * 2 + initSize;
- //pNew = sqlite3DbRealloc(db, pArray, newSize * szEntry);
- //if (pNew == 0)
- //{
- // pIdx = -1;
- // return pArray;
- //}
- pnAlloc = newSize; //sqlite3DbMallocSize(db, pNew)/szEntry;
- //pArray = pNew;
- Array.Resize( ref pArray, newSize );
- }
- pArray[pnEntry] = new T();
- //z = (char)pArray;
- //memset(z[*pnEntry * szEntry], 0, szEntry);
- pIdx = pnEntry;
- ++pnEntry;
- return pArray;
- }
+ /*
+ ** Append a new element to the given IdList. Create a new IdList if
+ ** need be.
+ **
+ ** A new IdList is returned, or NULL if malloc() fails.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static IdList sqlite3IdListAppend(sqlite3 db, int null_2, Token pToken) {
+ return sqlite3IdListAppend(db, null, pToken);
+ }
+ static IdList sqlite3IdListAppend(sqlite3 db, IdList pList, Token pToken) {
+ int i = 0;
+ if (pList == null) {
+ pList = new IdList();//sqlite3DbMallocZero(db, sizeof(IdList));
+ if (pList == null)
+ return null;
+ pList.nAlloc = 0;
+ }
+ pList.a = (IdList_item[])sqlite3ArrayAllocate(
+ db,
+ pList.a,
+ -1,//sizeof(pList.a[0]),
+ 5,
+ ref pList.nId,
+ ref pList.nAlloc,
+ ref i
+ );
+ if (i < 0) {
+ sqlite3IdListDelete(db, ref pList);
+ return null;
+ }
+ pList.a[i].zName = sqlite3NameFromToken(db, pToken);
+ return pList;
+ }
- /*
- ** Append a new element to the given IdList. Create a new IdList if
- ** need be.
- **
- ** A new IdList is returned, or NULL if malloc() fails.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static IdList sqlite3IdListAppend( sqlite3 db, int null_2, Token pToken )
- {
- return sqlite3IdListAppend( db, null, pToken );
- }
- static IdList sqlite3IdListAppend( sqlite3 db, IdList pList, Token pToken )
- {
- int i = 0;
- if ( pList == null )
- {
- pList = new IdList();//sqlite3DbMallocZero(db, sizeof(IdList));
- if ( pList == null )
- return null;
- pList.nAlloc = 0;
- }
- pList.a = (IdList_item[])sqlite3ArrayAllocate(
- db,
- pList.a,
- -1,//sizeof(pList.a[0]),
- 5,
- ref pList.nId,
- ref pList.nAlloc,
- ref i
- );
- if ( i < 0 )
- {
- sqlite3IdListDelete( db, ref pList );
- return null;
- }
- pList.a[i].zName = sqlite3NameFromToken( db, pToken );
- return pList;
- }
+ /*
+ ** Delete an IdList.
+ */
+ static void sqlite3IdListDelete(sqlite3 db, ref IdList pList) {
+ int i;
+ if (pList == null)
+ return;
+ for (i = 0; i < pList.nId; i++) {
+ sqlite3DbFree(db, ref pList.a[i].zName);
+ }
+ sqlite3DbFree(db, ref pList.a);
+ sqlite3DbFree(db, ref pList);
+ }
- /*
- ** Delete an IdList.
- */
- static void sqlite3IdListDelete( sqlite3 db, ref IdList pList )
- {
- int i;
- if ( pList == null )
- return;
- for ( i = 0; i < pList.nId; i++ )
- {
- sqlite3DbFree( db, ref pList.a[i].zName );
- }
- sqlite3DbFree( db, ref pList.a );
- sqlite3DbFree( db, ref pList );
- }
+ /*
+ ** Return the index in pList of the identifier named zId. Return -1
+ ** if not found.
+ */
+ static int sqlite3IdListIndex(IdList pList, string zName) {
+ int i;
+ if (pList == null)
+ return -1;
+ for (i = 0; i < pList.nId; i++) {
+ if (pList.a[i].zName.Equals(zName, StringComparison.OrdinalIgnoreCase))
+ return i;
+ }
+ return -1;
+ }
- /*
- ** Return the index in pList of the identifier named zId. Return -1
- ** if not found.
- */
- static int sqlite3IdListIndex( IdList pList, string zName )
- {
- int i;
- if ( pList == null )
- return -1;
- for ( i = 0; i < pList.nId; i++ )
- {
- if ( pList.a[i].zName.Equals( zName, StringComparison.OrdinalIgnoreCase ) )
- return i;
- }
- return -1;
- }
+ /*
+ ** Expand the space allocated for the given SrcList object by
+ ** creating nExtra new slots beginning at iStart. iStart is zero based.
+ ** New slots are zeroed.
+ **
+ ** For example, suppose a SrcList initially contains two entries: A,B.
+ ** To append 3 new entries onto the end, do this:
+ **
+ ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
+ **
+ ** After the call above it would contain: A, B, nil, nil, nil.
+ ** If the iStart argument had been 1 instead of 2, then the result
+ ** would have been: A, nil, nil, nil, B. To prepend the new slots,
+ ** the iStart value would be 0. The result then would
+ ** be: nil, nil, nil, A, B.
+ **
+ ** If a memory allocation fails the SrcList is unchanged. The
+ ** db.mallocFailed flag will be set to true.
+ */
+ static SrcList sqlite3SrcListEnlarge(
+ sqlite3 db, /* Database connection to notify of OOM errors */
+ SrcList pSrc, /* The SrcList to be enlarged */
+ int nExtra, /* Number of new slots to add to pSrc.a[] */
+ int iStart /* Index in pSrc.a[] of first new slot */
+ ) {
+ int i;
- /*
- ** Expand the space allocated for the given SrcList object by
- ** creating nExtra new slots beginning at iStart. iStart is zero based.
- ** New slots are zeroed.
- **
- ** For example, suppose a SrcList initially contains two entries: A,B.
- ** To append 3 new entries onto the end, do this:
- **
- ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
- **
- ** After the call above it would contain: A, B, nil, nil, nil.
- ** If the iStart argument had been 1 instead of 2, then the result
- ** would have been: A, nil, nil, nil, B. To prepend the new slots,
- ** the iStart value would be 0. The result then would
- ** be: nil, nil, nil, A, B.
- **
- ** If a memory allocation fails the SrcList is unchanged. The
- ** db.mallocFailed flag will be set to true.
- */
- static SrcList sqlite3SrcListEnlarge(
- sqlite3 db, /* Database connection to notify of OOM errors */
- SrcList pSrc, /* The SrcList to be enlarged */
- int nExtra, /* Number of new slots to add to pSrc.a[] */
- int iStart /* Index in pSrc.a[] of first new slot */
- )
- {
- int i;
-
- /* Sanity checking on calling parameters */
- Debug.Assert( iStart >= 0 );
- Debug.Assert( nExtra >= 1 );
- Debug.Assert( pSrc != null );
- Debug.Assert( iStart <= pSrc.nSrc );
-
- /* Allocate additional space if needed */
- if ( pSrc.nSrc + nExtra > pSrc.nAlloc )
- {
- int nAlloc = pSrc.nSrc + nExtra;
- int nGot;
- // sqlite3DbRealloc(db, pSrc,
- // sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc.a[0]) );
- pSrc.nAlloc = (i16)nAlloc;
- Array.Resize( ref pSrc.a, nAlloc );
- // nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
- //pSrc->nAlloc = (u16)nGot;
- }
-
- /* Move existing slots that come after the newly inserted slots
- ** out of the way */
- for ( i = pSrc.nSrc - 1; i >= iStart; i-- )
- {
- pSrc.a[i + nExtra] = pSrc.a[i];
- }
- pSrc.nSrc += (i16)nExtra;
-
- /* Zero the newly allocated slots */
- //memset(&pSrc.a[iStart], 0, sizeof(pSrc.a[0])*nExtra);
- for ( i = iStart; i < iStart + nExtra; i++ )
- {
- pSrc.a[i] = new SrcList_item();
- pSrc.a[i].iCursor = -1;
- }
-
- /* Return a pointer to the enlarged SrcList */
- return pSrc;
- }
+ /* Sanity checking on calling parameters */
+ Debug.Assert(iStart >= 0);
+ Debug.Assert(nExtra >= 1);
+ Debug.Assert(pSrc != null);
+ Debug.Assert(iStart <= pSrc.nSrc);
+
+ /* Allocate additional space if needed */
+ if (pSrc.nSrc + nExtra > pSrc.nAlloc) {
+ int nAlloc = pSrc.nSrc + nExtra;
+ int nGot;
+ // sqlite3DbRealloc(db, pSrc,
+ // sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc.a[0]) );
+ pSrc.nAlloc = (i16)nAlloc;
+ Array.Resize(ref pSrc.a, nAlloc);
+ // nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
+ //pSrc->nAlloc = (u16)nGot;
+ }
+ /* Move existing slots that come after the newly inserted slots
+ ** out of the way */
+ for (i = pSrc.nSrc - 1; i >= iStart; i--) {
+ pSrc.a[i + nExtra] = pSrc.a[i];
+ }
+ pSrc.nSrc += (i16)nExtra;
- /*
- ** Append a new table name to the given SrcList. Create a new SrcList if
- ** need be. A new entry is created in the SrcList even if pTable is NULL.
- **
- ** A SrcList is returned, or NULL if there is an OOM error. The returned
- ** SrcList might be the same as the SrcList that was input or it might be
- ** a new one. If an OOM error does occurs, then the prior value of pList
- ** that is input to this routine is automatically freed.
- **
- ** If pDatabase is not null, it means that the table has an optional
- ** database name prefix. Like this: "database.table". The pDatabase
- ** points to the table name and the pTable points to the database name.
- ** The SrcList.a[].zName field is filled with the table name which might
- ** come from pTable (if pDatabase is NULL) or from pDatabase.
- ** SrcList.a[].zDatabase is filled with the database name from pTable,
- ** or with NULL if no database is specified.
- **
- ** In other words, if call like this:
- **
- ** sqlite3SrcListAppend(D,A,B,0);
- **
- ** Then B is a table name and the database name is unspecified. If called
- ** like this:
- **
- ** sqlite3SrcListAppend(D,A,B,C);
- **
- ** Then C is the table name and B is the database name. If C is defined
- ** then so is B. In other words, we never have a case where:
- **
- ** sqlite3SrcListAppend(D,A,0,C);
- **
- ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
- ** before being added to the SrcList.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, int null_4 )
- {
- return sqlite3SrcListAppend( db, null, pTable, null );
- }
- static SrcList sqlite3SrcListAppend( sqlite3 db, int null_2, Token pTable, Token pDatabase )
- {
- return sqlite3SrcListAppend( db, null, pTable, pDatabase );
- }
- static SrcList sqlite3SrcListAppend(
- sqlite3 db, /* Connection to notify of malloc failures */
- SrcList pList, /* Append to this SrcList. NULL creates a new SrcList */
- Token pTable, /* Table to append */
- Token pDatabase /* Database of the table */
- )
- {
- SrcList_item pItem;
- Debug.Assert( pDatabase == null || pTable != null ); /* Cannot have C without B */
- if ( pList == null )
- {
- pList = new SrcList();//sqlite3DbMallocZero(db, SrcList.Length );
- //if ( pList == null ) return null;
- pList.nAlloc = 1;
- pList.a = new SrcList_item[1];
- }
- pList = sqlite3SrcListEnlarge( db, pList, 1, pList.nSrc );
- //if ( db.mallocFailed != 0 )
- //{
- // sqlite3SrcListDelete( db, ref pList );
- // return null;
- //}
- pItem = pList.a[pList.nSrc - 1];
- if ( pDatabase != null && String.IsNullOrEmpty( pDatabase.z ) )
- {
- pDatabase = null;
- }
- if ( pDatabase != null )
- {
- Token pTemp = pDatabase;
- pDatabase = pTable;
- pTable = pTemp;
- }
- pItem.zName = sqlite3NameFromToken( db, pTable );
- pItem.zDatabase = sqlite3NameFromToken( db, pDatabase );
- return pList;
- }
+ /* Zero the newly allocated slots */
+ //memset(&pSrc.a[iStart], 0, sizeof(pSrc.a[0])*nExtra);
+ for (i = iStart; i < iStart + nExtra; i++) {
+ pSrc.a[i] = new SrcList_item();
+ pSrc.a[i].iCursor = -1;
+ }
- /*
- ** Assign VdbeCursor index numbers to all tables in a SrcList
- */
- static void sqlite3SrcListAssignCursors( Parse pParse, SrcList pList )
- {
- int i;
- SrcList_item pItem;
- Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ );
- if ( pList != null )
- {
- for ( i = 0; i < pList.nSrc; i++ )
- {
- pItem = pList.a[i];
- if ( pItem.iCursor >= 0 )
- break;
- pItem.iCursor = pParse.nTab++;
- if ( pItem.pSelect != null )
- {
- sqlite3SrcListAssignCursors( pParse, pItem.pSelect.pSrc );
- }
+ /* Return a pointer to the enlarged SrcList */
+ return pSrc;
}
- }
- }
- /*
- ** Delete an entire SrcList including all its substructure.
- */
- static void sqlite3SrcListDelete( sqlite3 db, ref SrcList pList )
- {
- int i;
- SrcList_item pItem;
- if ( pList == null )
- return;
- for ( i = 0; i < pList.nSrc; i++ )
- {//, pItem++){
- pItem = pList.a[i];
- sqlite3DbFree( db, ref pItem.zDatabase );
- sqlite3DbFree( db, ref pItem.zName );
- sqlite3DbFree( db, ref pItem.zAlias );
- sqlite3DbFree( db, ref pItem.zIndex );
- sqlite3DeleteTable( db, ref pItem.pTab );
- sqlite3SelectDelete( db, ref pItem.pSelect );
- sqlite3ExprDelete( db, ref pItem.pOn );
- sqlite3IdListDelete( db, ref pItem.pUsing );
- }
- sqlite3DbFree( db, ref pList );
- }
- /*
- ** This routine is called by the parser to add a new term to the
- ** end of a growing FROM clause. The "p" parameter is the part of
- ** the FROM clause that has already been constructed. "p" is NULL
- ** if this is the first term of the FROM clause. pTable and pDatabase
- ** are the name of the table and database named in the FROM clause term.
- ** pDatabase is NULL if the database name qualifier is missing - the
- ** usual case. If the term has a alias, then pAlias points to the
- ** alias token. If the term is a subquery, then pSubquery is the
- ** SELECT statement that the subquery encodes. The pTable and
- ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
- ** parameters are the content of the ON and USING clauses.
- **
- ** Return a new SrcList which encodes is the FROM with the new
- ** term added.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, int null_3, int null_4, Token pAlias, Select pSubquery, Expr pOn, IdList pUsing )
- {
- return sqlite3SrcListAppendFromTerm( pParse, p, null, null, pAlias, pSubquery, pOn, pUsing );
- }
- static SrcList sqlite3SrcListAppendFromTerm( Parse pParse, SrcList p, Token pTable, Token pDatabase, Token pAlias, int null_6, Expr pOn, IdList pUsing )
- {
- return sqlite3SrcListAppendFromTerm( pParse, p, pTable, pDatabase, pAlias, null, pOn, pUsing );
- }
- static SrcList sqlite3SrcListAppendFromTerm(
- Parse pParse, /* Parsing context */
- SrcList p, /* The left part of the FROM clause already seen */
- Token pTable, /* Name of the table to add to the FROM clause */
- Token pDatabase, /* Name of the database containing pTable */
- Token pAlias, /* The right-hand side of the AS subexpression */
- Select pSubquery, /* A subquery used in place of a table name */
- Expr pOn, /* The ON clause of a join */
- IdList pUsing /* The USING clause of a join */
- )
- {
- SrcList_item pItem;
- sqlite3 db = pParse.db;
- if ( null == p && ( pOn != null || pUsing != null ) )
- {
- sqlite3ErrorMsg( pParse, "a JOIN clause is required before %s",
- ( pOn != null ? "ON" : "USING" )
- );
- goto append_from_error;
- }
- p = sqlite3SrcListAppend( db, p, pTable, pDatabase );
- //if ( p == null || NEVER( p.nSrc == 0 ) )
- //{
- // goto append_from_error;
- //}
- pItem = p.a[p.nSrc - 1];
- Debug.Assert( pAlias != null );
- if ( pAlias.n != 0 )
- {
- pItem.zAlias = sqlite3NameFromToken( db, pAlias );
- }
- pItem.pSelect = pSubquery;
- pItem.pOn = pOn;
- pItem.pUsing = pUsing;
- return p;
-append_from_error:
- Debug.Assert( p == null );
- sqlite3ExprDelete( db, ref pOn );
- sqlite3IdListDelete( db, ref pUsing );
- sqlite3SelectDelete( db, ref pSubquery );
- return null;
- }
+ /*
+ ** Append a new table name to the given SrcList. Create a new SrcList if
+ ** need be. A new entry is created in the SrcList even if pTable is NULL.
+ **
+ ** A SrcList is returned, or NULL if there is an OOM error. The returned
+ ** SrcList might be the same as the SrcList that was input or it might be
+ ** a new one. If an OOM error does occurs, then the prior value of pList
+ ** that is input to this routine is automatically freed.
+ **
+ ** If pDatabase is not null, it means that the table has an optional
+ ** database name prefix. Like this: "database.table". The pDatabase
+ ** points to the table name and the pTable points to the database name.
+ ** The SrcList.a[].zName field is filled with the table name which might
+ ** come from pTable (if pDatabase is NULL) or from pDatabase.
+ ** SrcList.a[].zDatabase is filled with the database name from pTable,
+ ** or with NULL if no database is specified.
+ **
+ ** In other words, if call like this:
+ **
+ ** sqlite3SrcListAppend(D,A,B,0);
+ **
+ ** Then B is a table name and the database name is unspecified. If called
+ ** like this:
+ **
+ ** sqlite3SrcListAppend(D,A,B,C);
+ **
+ ** Then C is the table name and B is the database name. If C is defined
+ ** then so is B. In other words, we never have a case where:
+ **
+ ** sqlite3SrcListAppend(D,A,0,C);
+ **
+ ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
+ ** before being added to the SrcList.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static SrcList sqlite3SrcListAppend(sqlite3 db, int null_2, Token pTable, int null_4) {
+ return sqlite3SrcListAppend(db, null, pTable, null);
+ }
+ static SrcList sqlite3SrcListAppend(sqlite3 db, int null_2, Token pTable, Token pDatabase) {
+ return sqlite3SrcListAppend(db, null, pTable, pDatabase);
+ }
+ static SrcList sqlite3SrcListAppend(
+ sqlite3 db, /* Connection to notify of malloc failures */
+ SrcList pList, /* Append to this SrcList. NULL creates a new SrcList */
+ Token pTable, /* Table to append */
+ Token pDatabase /* Database of the table */
+ ) {
+ SrcList_item pItem;
+ Debug.Assert(pDatabase == null || pTable != null); /* Cannot have C without B */
+ if (pList == null) {
+ pList = new SrcList();//sqlite3DbMallocZero(db, SrcList.Length );
+ //if ( pList == null ) return null;
+ pList.nAlloc = 1;
+ pList.a = new SrcList_item[1];
+ }
+ pList = sqlite3SrcListEnlarge(db, pList, 1, pList.nSrc);
+ //if ( db.mallocFailed != 0 )
+ //{
+ // sqlite3SrcListDelete( db, ref pList );
+ // return null;
+ //}
+ pItem = pList.a[pList.nSrc - 1];
+ if (pDatabase != null && String.IsNullOrEmpty(pDatabase.z)) {
+ pDatabase = null;
+ }
+ if (pDatabase != null) {
+ Token pTemp = pDatabase;
+ pDatabase = pTable;
+ pTable = pTemp;
+ }
+ pItem.zName = sqlite3NameFromToken(db, pTable);
+ pItem.zDatabase = sqlite3NameFromToken(db, pDatabase);
+ return pList;
+ }
- /*
- ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
- ** element of the source-list passed as the second argument.
- */
- static void sqlite3SrcListIndexedBy( Parse pParse, SrcList p, Token pIndexedBy )
- {
- Debug.Assert( pIndexedBy != null );
- if ( p != null && ALWAYS( p.nSrc > 0 ) )
- {
- SrcList_item pItem = p.a[p.nSrc - 1];
- Debug.Assert( 0 == pItem.notIndexed && pItem.zIndex == null );
- if ( pIndexedBy.n == 1 && null == pIndexedBy.z )
- {
- /* A "NOT INDEXED" clause was supplied. See parse.y
- ** construct "indexed_opt" for details. */
- pItem.notIndexed = 1;
+ /*
+ ** Assign VdbeCursor index numbers to all tables in a SrcList
+ */
+ static void sqlite3SrcListAssignCursors(Parse pParse, SrcList pList) {
+ int i;
+ SrcList_item pItem;
+ Debug.Assert(pList != null /* || pParse.db.mallocFailed != 0 */ );
+ if (pList != null) {
+ for (i = 0; i < pList.nSrc; i++) {
+ pItem = pList.a[i];
+ if (pItem.iCursor >= 0)
+ break;
+ pItem.iCursor = pParse.nTab++;
+ if (pItem.pSelect != null) {
+ sqlite3SrcListAssignCursors(pParse, pItem.pSelect.pSrc);
+ }
+ }
+ }
}
- else
- {
- pItem.zIndex = sqlite3NameFromToken( pParse.db, pIndexedBy );
+
+ /*
+ ** Delete an entire SrcList including all its substructure.
+ */
+ static void sqlite3SrcListDelete(sqlite3 db, ref SrcList pList) {
+ int i;
+ SrcList_item pItem;
+ if (pList == null)
+ return;
+ for (i = 0; i < pList.nSrc; i++) {//, pItem++){
+ pItem = pList.a[i];
+ sqlite3DbFree(db, ref pItem.zDatabase);
+ sqlite3DbFree(db, ref pItem.zName);
+ sqlite3DbFree(db, ref pItem.zAlias);
+ sqlite3DbFree(db, ref pItem.zIndex);
+ sqlite3DeleteTable(db, ref pItem.pTab);
+ sqlite3SelectDelete(db, ref pItem.pSelect);
+ sqlite3ExprDelete(db, ref pItem.pOn);
+ sqlite3IdListDelete(db, ref pItem.pUsing);
+ }
+ sqlite3DbFree(db, ref pList);
}
- }
- }
- /*
- ** When building up a FROM clause in the parser, the join operator
- ** is initially attached to the left operand. But the code generator
- ** expects the join operator to be on the right operand. This routine
- ** Shifts all join operators from left to right for an entire FROM
- ** clause.
- **
- ** Example: Suppose the join is like this:
- **
- ** A natural cross join B
- **
- ** The operator is "natural cross join". The A and B operands are stored
- ** in p.a[0] and p.a[1], respectively. The parser initially stores the
- ** operator with A. This routine shifts that operator over to B.
- */
- static void sqlite3SrcListShiftJoinType( SrcList p )
- {
- if ( p != null && p.a != null )
- {
- int i;
- for ( i = p.nSrc - 1; i > 0; i-- )
- {
- p.a[i].jointype = p.a[i - 1].jointype;
+ /*
+ ** This routine is called by the parser to add a new term to the
+ ** end of a growing FROM clause. The "p" parameter is the part of
+ ** the FROM clause that has already been constructed. "p" is NULL
+ ** if this is the first term of the FROM clause. pTable and pDatabase
+ ** are the name of the table and database named in the FROM clause term.
+ ** pDatabase is NULL if the database name qualifier is missing - the
+ ** usual case. If the term has a alias, then pAlias points to the
+ ** alias token. If the term is a subquery, then pSubquery is the
+ ** SELECT statement that the subquery encodes. The pTable and
+ ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
+ ** parameters are the content of the ON and USING clauses.
+ **
+ ** Return a new SrcList which encodes is the FROM with the new
+ ** term added.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static SrcList sqlite3SrcListAppendFromTerm(Parse pParse, SrcList p, int null_3, int null_4, Token pAlias, Select pSubquery, Expr pOn, IdList pUsing) {
+ return sqlite3SrcListAppendFromTerm(pParse, p, null, null, pAlias, pSubquery, pOn, pUsing);
+ }
+ static SrcList sqlite3SrcListAppendFromTerm(Parse pParse, SrcList p, Token pTable, Token pDatabase, Token pAlias, int null_6, Expr pOn, IdList pUsing) {
+ return sqlite3SrcListAppendFromTerm(pParse, p, pTable, pDatabase, pAlias, null, pOn, pUsing);
+ }
+ static SrcList sqlite3SrcListAppendFromTerm(
+ Parse pParse, /* Parsing context */
+ SrcList p, /* The left part of the FROM clause already seen */
+ Token pTable, /* Name of the table to add to the FROM clause */
+ Token pDatabase, /* Name of the database containing pTable */
+ Token pAlias, /* The right-hand side of the AS subexpression */
+ Select pSubquery, /* A subquery used in place of a table name */
+ Expr pOn, /* The ON clause of a join */
+ IdList pUsing /* The USING clause of a join */
+ ) {
+ SrcList_item pItem;
+ sqlite3 db = pParse.db;
+ if (null == p && (pOn != null || pUsing != null)) {
+ sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
+ (pOn != null ? "ON" : "USING")
+ );
+ goto append_from_error;
+ }
+ p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
+ //if ( p == null || NEVER( p.nSrc == 0 ) )
+ //{
+ // goto append_from_error;
+ //}
+ pItem = p.a[p.nSrc - 1];
+ Debug.Assert(pAlias != null);
+ if (pAlias.n != 0) {
+ pItem.zAlias = sqlite3NameFromToken(db, pAlias);
+ }
+ pItem.pSelect = pSubquery;
+ pItem.pOn = pOn;
+ pItem.pUsing = pUsing;
+ return p;
+ append_from_error:
+ Debug.Assert(p == null);
+ sqlite3ExprDelete(db, ref pOn);
+ sqlite3IdListDelete(db, ref pUsing);
+ sqlite3SelectDelete(db, ref pSubquery);
+ return null;
}
- p.a[0].jointype = 0;
- }
- }
- /*
- ** Begin a transaction
- */
- static void sqlite3BeginTransaction( Parse pParse, int type )
- {
- sqlite3 db;
- Vdbe v;
- int i;
-
- Debug.Assert( pParse != null );
- db = pParse.db;
- Debug.Assert( db != null );
- /* if( db.aDb[0].pBt==0 ) return; */
- if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "BEGIN", null, null ) != 0 )
- {
- return;
- }
- v = sqlite3GetVdbe( pParse );
- if ( v == null )
- return;
- if ( type != TK_DEFERRED )
- {
- for ( i = 0; i < db.nDb; i++ )
- {
- sqlite3VdbeAddOp2( v, OP_Transaction, i, ( type == TK_EXCLUSIVE ) ? 2 : 1 );
- sqlite3VdbeUsesBtree( v, i );
+ /*
+ ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
+ ** element of the source-list passed as the second argument.
+ */
+ static void sqlite3SrcListIndexedBy(Parse pParse, SrcList p, Token pIndexedBy) {
+ Debug.Assert(pIndexedBy != null);
+ if (p != null && ALWAYS(p.nSrc > 0)) {
+ SrcList_item pItem = p.a[p.nSrc - 1];
+ Debug.Assert(0 == pItem.notIndexed && pItem.zIndex == null);
+ if (pIndexedBy.n == 1 && null == pIndexedBy.z) {
+ /* A "NOT INDEXED" clause was supplied. See parse.y
+ ** construct "indexed_opt" for details. */
+ pItem.notIndexed = 1;
+ } else {
+ pItem.zIndex = sqlite3NameFromToken(pParse.db, pIndexedBy);
+ }
+ }
}
- }
- sqlite3VdbeAddOp2( v, OP_AutoCommit, 0, 0 );
- }
- /*
- ** Commit a transaction
- */
- static void sqlite3CommitTransaction( Parse pParse )
- {
- sqlite3 db;
- Vdbe v;
-
- Debug.Assert( pParse != null );
- db = pParse.db;
- Debug.Assert( db != null );
- /* if( db.aDb[0].pBt==0 ) return; */
- if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "COMMIT", null, null ) != 0 )
- {
- return;
- }
- v = sqlite3GetVdbe( pParse );
- if ( v != null )
- {
- sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 0 );
- }
- }
+ /*
+ ** When building up a FROM clause in the parser, the join operator
+ ** is initially attached to the left operand. But the code generator
+ ** expects the join operator to be on the right operand. This routine
+ ** Shifts all join operators from left to right for an entire FROM
+ ** clause.
+ **
+ ** Example: Suppose the join is like this:
+ **
+ ** A natural cross join B
+ **
+ ** The operator is "natural cross join". The A and B operands are stored
+ ** in p.a[0] and p.a[1], respectively. The parser initially stores the
+ ** operator with A. This routine shifts that operator over to B.
+ */
+ static void sqlite3SrcListShiftJoinType(SrcList p) {
+ if (p != null && p.a != null) {
+ int i;
+ for (i = p.nSrc - 1; i > 0; i--) {
+ p.a[i].jointype = p.a[i - 1].jointype;
+ }
+ p.a[0].jointype = 0;
+ }
+ }
- /*
- ** Rollback a transaction
- */
- static void sqlite3RollbackTransaction( Parse pParse )
- {
- sqlite3 db;
- Vdbe v;
-
- Debug.Assert( pParse != null );
- db = pParse.db;
- Debug.Assert( db != null );
- /* if( db.aDb[0].pBt==0 ) return; */
- if ( sqlite3AuthCheck( pParse, SQLITE_TRANSACTION, "ROLLBACK", null, null ) != 0 )
- {
- return;
- }
- v = sqlite3GetVdbe( pParse );
- if ( v != null )
- {
- sqlite3VdbeAddOp2( v, OP_AutoCommit, 1, 1 );
- }
- }
+ /*
+ ** Begin a transaction
+ */
+ static void sqlite3BeginTransaction(Parse pParse, int type) {
+ sqlite3 db;
+ Vdbe v;
+ int i;
- /*
- ** This function is called by the parser when it parses a command to create,
- ** release or rollback an SQL savepoint.
- */
+ Debug.Assert(pParse != null);
+ db = pParse.db;
+ Debug.Assert(db != null);
+ /* if( db.aDb[0].pBt==0 ) return; */
+ if (sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", null, null) != 0) {
+ return;
+ }
+ v = sqlite3GetVdbe(pParse);
+ if (v == null)
+ return;
+ if (type != TK_DEFERRED) {
+ for (i = 0; i < db.nDb; i++) {
+ sqlite3VdbeAddOp2(v, OP_Transaction, i, (type == TK_EXCLUSIVE) ? 2 : 1);
+ sqlite3VdbeUsesBtree(v, i);
+ }
+ }
+ sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
+ }
+
+ /*
+ ** Commit a transaction
+ */
+ static void sqlite3CommitTransaction(Parse pParse) {
+ sqlite3 db;
+ Vdbe v;
+
+ Debug.Assert(pParse != null);
+ db = pParse.db;
+ Debug.Assert(db != null);
+ /* if( db.aDb[0].pBt==0 ) return; */
+ if (sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", null, null) != 0) {
+ return;
+ }
+ v = sqlite3GetVdbe(pParse);
+ if (v != null) {
+ sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
+ }
+ }
+
+ /*
+ ** Rollback a transaction
+ */
+ static void sqlite3RollbackTransaction(Parse pParse) {
+ sqlite3 db;
+ Vdbe v;
+
+ Debug.Assert(pParse != null);
+ db = pParse.db;
+ Debug.Assert(db != null);
+ /* if( db.aDb[0].pBt==0 ) return; */
+ if (sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", null, null) != 0) {
+ return;
+ }
+ v = sqlite3GetVdbe(pParse);
+ if (v != null) {
+ sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
+ }
+ }
+
+ /*
+ ** This function is called by the parser when it parses a command to create,
+ ** release or rollback an SQL savepoint.
+ */
#if !SQLITE_OMIT_AUTHORIZATION
const string[] az = { "BEGIN", "RELEASE", "ROLLBACK" };
#endif
- static void sqlite3Savepoint( Parse pParse, int op, Token pName )
- {
- string zName = sqlite3NameFromToken( pParse.db, pName );
- if ( zName != null )
- {
- Vdbe v = sqlite3GetVdbe( pParse );
+ static void sqlite3Savepoint(Parse pParse, int op, Token pName) {
+ string zName = sqlite3NameFromToken(pParse.db, pName);
+ if (zName != null) {
+ Vdbe v = sqlite3GetVdbe(pParse);
#if !SQLITE_OMIT_AUTHORIZATION
Debug.Assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
#endif
- if ( null == v
+ if (null == v
#if !SQLITE_OMIT_AUTHORIZATION
|| sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0)
#endif
- )
- {
- sqlite3DbFree( pParse.db, ref zName );
- return;
+ ) {
+ sqlite3DbFree(pParse.db, ref zName);
+ return;
+ }
+ sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
+ }
}
- sqlite3VdbeAddOp4( v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC );
- }
- }
- /*
- ** Make sure the TEMP database is open and available for use. Return
- ** the number of errors. Leave any error messages in the pParse structure.
- */
- static int sqlite3OpenTempDatabase( Parse pParse )
- {
- sqlite3 db = pParse.db;
- if ( db.aDb[1].pBt == null && pParse.explain == 0 )
- {
- int rc;
- Btree pBt = null;
- const int flags =
- SQLITE_OPEN_READWRITE |
- SQLITE_OPEN_CREATE |
- SQLITE_OPEN_EXCLUSIVE |
- SQLITE_OPEN_DELETEONCLOSE |
- SQLITE_OPEN_TEMP_DB;
-
- rc = sqlite3BtreeOpen(db.pVfs, null, db, ref pBt, 0, flags );
- if ( rc != SQLITE_OK )
- {
- sqlite3ErrorMsg( pParse, "unable to open a temporary database " +
- "file for storing temporary tables" );
- pParse.rc = rc;
- return 1;
- }
- db.aDb[1].pBt = pBt;
- Debug.Assert( db.aDb[1].pSchema != null );
- if ( SQLITE_NOMEM == sqlite3BtreeSetPageSize( pBt, db.nextPagesize, -1, 0 ) )
- {
- // db.mallocFailed = 1;
+ /*
+ ** Make sure the TEMP database is open and available for use. Return
+ ** the number of errors. Leave any error messages in the pParse structure.
+ */
+ static int sqlite3OpenTempDatabase(Parse pParse) {
+ sqlite3 db = pParse.db;
+ if (db.aDb[1].pBt == null && pParse.explain == 0) {
+ int rc;
+ Btree pBt = null;
+ const int flags =
+ SQLITE_OPEN_READWRITE |
+ SQLITE_OPEN_CREATE |
+ SQLITE_OPEN_EXCLUSIVE |
+ SQLITE_OPEN_DELETEONCLOSE |
+ SQLITE_OPEN_TEMP_DB;
+
+ rc = sqlite3BtreeOpen(db.pVfs, null, db, ref pBt, 0, flags);
+ if (rc != SQLITE_OK) {
+ sqlite3ErrorMsg(pParse, "unable to open a temporary database " +
+ "file for storing temporary tables");
+ pParse.rc = rc;
+ return 1;
+ }
+ db.aDb[1].pBt = pBt;
+ Debug.Assert(db.aDb[1].pSchema != null);
+ if (SQLITE_NOMEM == sqlite3BtreeSetPageSize(pBt, db.nextPagesize, -1, 0)) {
+ // db.mallocFailed = 1;
+ }
+ }
+ return 0;
}
- }
- return 0;
- }
- /*
- ** Generate VDBE code that will verify the schema cookie and start
- ** a read-transaction for all named database files.
- **
- ** It is important that all schema cookies be verified and all
- ** read transactions be started before anything else happens in
- ** the VDBE program. But this routine can be called after much other
- ** code has been generated. So here is what we do:
- **
- ** The first time this routine is called, we code an OP_Goto that
- ** will jump to a subroutine at the end of the program. Then we
- ** record every database that needs its schema verified in the
- ** pParse.cookieMask field. Later, after all other code has been
- ** generated, the subroutine that does the cookie verifications and
- ** starts the transactions will be coded and the OP_Goto P2 value
- ** will be made to point to that subroutine. The generation of the
- ** cookie verification subroutine code happens in sqlite3FinishCoding().
- **
- ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
- ** schema on any databases. This can be used to position the OP_Goto
- ** early in the code, before we know if any database tables will be used.
- */
- static void sqlite3CodeVerifySchema( Parse pParse, int iDb )
- {
- Parse pToplevel = sqlite3ParseToplevel( pParse );
-
- if ( pToplevel.cookieGoto == 0 )
- {
- Vdbe v = sqlite3GetVdbe( pToplevel );
- if ( v == null )
- return; /* This only happens if there was a prior error */
- pToplevel.cookieGoto = sqlite3VdbeAddOp2( v, OP_Goto, 0, 0 ) + 1;
- }
- if ( iDb >= 0 )
- {
- sqlite3 db = pToplevel.db;
- yDbMask mask;
- Debug.Assert( iDb < db.nDb );
- Debug.Assert( db.aDb[iDb].pBt != null || iDb == 1 );
- Debug.Assert( iDb < SQLITE_MAX_ATTACHED + 2 );
- Debug.Assert( sqlite3SchemaMutexHeld( db, iDb, null ) );
- mask = ( (yDbMask)1 ) << iDb;
- if ( ( pToplevel.cookieMask & mask ) == 0 )
- {
- pToplevel.cookieMask |= mask;
- pToplevel.cookieValue[iDb] = db.aDb[iDb].pSchema.schema_cookie;
- if ( 0 == OMIT_TEMPDB && iDb == 1 )
- {
- sqlite3OpenTempDatabase( pToplevel );
- }
+ /*
+ ** Generate VDBE code that will verify the schema cookie and start
+ ** a read-transaction for all named database files.
+ **
+ ** It is important that all schema cookies be verified and all
+ ** read transactions be started before anything else happens in
+ ** the VDBE program. But this routine can be called after much other
+ ** code has been generated. So here is what we do:
+ **
+ ** The first time this routine is called, we code an OP_Goto that
+ ** will jump to a subroutine at the end of the program. Then we
+ ** record every database that needs its schema verified in the
+ ** pParse.cookieMask field. Later, after all other code has been
+ ** generated, the subroutine that does the cookie verifications and
+ ** starts the transactions will be coded and the OP_Goto P2 value
+ ** will be made to point to that subroutine. The generation of the
+ ** cookie verification subroutine code happens in sqlite3FinishCoding().
+ **
+ ** If iDb<0 then code the OP_Goto only - don't set flag to verify the
+ ** schema on any databases. This can be used to position the OP_Goto
+ ** early in the code, before we know if any database tables will be used.
+ */
+ static void sqlite3CodeVerifySchema(Parse pParse, int iDb) {
+ Parse pToplevel = sqlite3ParseToplevel(pParse);
+
+ if (pToplevel.cookieGoto == 0) {
+ Vdbe v = sqlite3GetVdbe(pToplevel);
+ if (v == null)
+ return; /* This only happens if there was a prior error */
+ pToplevel.cookieGoto = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0) + 1;
+ }
+ if (iDb >= 0) {
+ sqlite3 db = pToplevel.db;
+ yDbMask mask;
+ Debug.Assert(iDb < db.nDb);
+ Debug.Assert(db.aDb[iDb].pBt != null || iDb == 1);
+ Debug.Assert(iDb < SQLITE_MAX_ATTACHED + 2);
+ Debug.Assert(sqlite3SchemaMutexHeld(db, iDb, null));
+ mask = ((yDbMask)1) << iDb;
+ if ((pToplevel.cookieMask & mask) == 0) {
+ pToplevel.cookieMask |= mask;
+ pToplevel.cookieValue[iDb] = db.aDb[iDb].pSchema.schema_cookie;
+ if (0 == OMIT_TEMPDB && iDb == 1) {
+ sqlite3OpenTempDatabase(pToplevel);
+ }
+ }
+ }
}
- }
- }
- /*
- ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
- ** attached database. Otherwise, invoke it for the database named zDb only.
- */
- static void sqlite3CodeVerifyNamedSchema( Parse pParse, string zDb )
- {
- sqlite3 db = pParse.db;
- int i;
- for ( i = 0; i < db.nDb; i++ )
- {
- Db pDb = db.aDb[i];
- if ( pDb.pBt != null && ( null == zDb || string.Equals( zDb, pDb.zName, StringComparison.Ordinal ) ) )
- {
- sqlite3CodeVerifySchema( pParse, i );
+ /*
+ ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
+ ** attached database. Otherwise, invoke it for the database named zDb only.
+ */
+ static void sqlite3CodeVerifyNamedSchema(Parse pParse, string zDb) {
+ sqlite3 db = pParse.db;
+ int i;
+ for (i = 0; i < db.nDb; i++) {
+ Db pDb = db.aDb[i];
+ if (pDb.pBt != null && (null == zDb || string.Equals(zDb, pDb.zName, StringComparison.Ordinal))) {
+ sqlite3CodeVerifySchema(pParse, i);
+ }
+ }
+ }
+ /*
+ ** Generate VDBE code that prepares for doing an operation that
+ ** might change the database.
+ **
+ ** This routine starts a new transaction if we are not already within
+ ** a transaction. If we are already within a transaction, then a checkpoint
+ ** is set if the setStatement parameter is true. A checkpoint should
+ ** be set for operations that might fail (due to a constraint) part of
+ ** the way through and which will need to undo some writes without having to
+ ** rollback the whole transaction. For operations where all constraints
+ ** can be checked before any changes are made to the database, it is never
+ ** necessary to undo a write and the checkpoint should not be set.
+ */
+ static void sqlite3BeginWriteOperation(Parse pParse, int setStatement, int iDb) {
+ Parse pToplevel = sqlite3ParseToplevel(pParse);
+ sqlite3CodeVerifySchema(pParse, iDb);
+ pToplevel.writeMask |= ((yDbMask)1) << iDb;
+ pToplevel.isMultiWrite |= (u8)setStatement;
}
- }
- }
- /*
- ** Generate VDBE code that prepares for doing an operation that
- ** might change the database.
- **
- ** This routine starts a new transaction if we are not already within
- ** a transaction. If we are already within a transaction, then a checkpoint
- ** is set if the setStatement parameter is true. A checkpoint should
- ** be set for operations that might fail (due to a constraint) part of
- ** the way through and which will need to undo some writes without having to
- ** rollback the whole transaction. For operations where all constraints
- ** can be checked before any changes are made to the database, it is never
- ** necessary to undo a write and the checkpoint should not be set.
- */
- static void sqlite3BeginWriteOperation( Parse pParse, int setStatement, int iDb )
- {
- Parse pToplevel = sqlite3ParseToplevel( pParse );
- sqlite3CodeVerifySchema( pParse, iDb );
- pToplevel.writeMask |= ( (yDbMask)1 ) << iDb;
- pToplevel.isMultiWrite |= (u8)setStatement;
- }
- /*
- ** Indicate that the statement currently under construction might write
- ** more than one entry (example: deleting one row then inserting another,
- ** inserting multiple rows in a table, or inserting a row and index entries.)
- ** If an abort occurs after some of these writes have completed, then it will
- ** be necessary to undo the completed writes.
- */
- static void sqlite3MultiWrite( Parse pParse )
- {
- Parse pToplevel = sqlite3ParseToplevel( pParse );
- pToplevel.isMultiWrite = 1;
- }
+ /*
+ ** Indicate that the statement currently under construction might write
+ ** more than one entry (example: deleting one row then inserting another,
+ ** inserting multiple rows in a table, or inserting a row and index entries.)
+ ** If an abort occurs after some of these writes have completed, then it will
+ ** be necessary to undo the completed writes.
+ */
+ static void sqlite3MultiWrite(Parse pParse) {
+ Parse pToplevel = sqlite3ParseToplevel(pParse);
+ pToplevel.isMultiWrite = 1;
+ }
- /*
- ** The code generator calls this routine if is discovers that it is
- ** possible to abort a statement prior to completion. In order to
- ** perform this abort without corrupting the database, we need to make
- ** sure that the statement is protected by a statement transaction.
- **
- ** Technically, we only need to set the mayAbort flag if the
- ** isMultiWrite flag was previously set. There is a time dependency
- ** such that the abort must occur after the multiwrite. This makes
- ** some statements involving the REPLACE conflict resolution algorithm
- ** go a little faster. But taking advantage of this time dependency
- ** makes it more difficult to prove that the code is correct (in
- ** particular, it prevents us from writing an effective
- ** implementation of sqlite3AssertMayAbort()) and so we have chosen
- ** to take the safe route and skip the optimization.
- */
- static void sqlite3MayAbort( Parse pParse )
- {
- Parse pToplevel = sqlite3ParseToplevel( pParse );
- pToplevel.mayAbort = 1;
- }
+ /*
+ ** The code generator calls this routine if is discovers that it is
+ ** possible to abort a statement prior to completion. In order to
+ ** perform this abort without corrupting the database, we need to make
+ ** sure that the statement is protected by a statement transaction.
+ **
+ ** Technically, we only need to set the mayAbort flag if the
+ ** isMultiWrite flag was previously set. There is a time dependency
+ ** such that the abort must occur after the multiwrite. This makes
+ ** some statements involving the REPLACE conflict resolution algorithm
+ ** go a little faster. But taking advantage of this time dependency
+ ** makes it more difficult to prove that the code is correct (in
+ ** particular, it prevents us from writing an effective
+ ** implementation of sqlite3AssertMayAbort()) and so we have chosen
+ ** to take the safe route and skip the optimization.
+ */
+ static void sqlite3MayAbort(Parse pParse) {
+ Parse pToplevel = sqlite3ParseToplevel(pParse);
+ pToplevel.mayAbort = 1;
+ }
- /*
- ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
- ** error. The onError parameter determines which (if any) of the statement
- ** and/or current transaction is rolled back.
- */
- static void sqlite3HaltConstraint( Parse pParse, int onError, string p4, int p4type )
- {
- Vdbe v = sqlite3GetVdbe( pParse );
- if ( onError == OE_Abort )
- {
- sqlite3MayAbort( pParse );
- }
- sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type );
- }
+ /*
+ ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
+ ** error. The onError parameter determines which (if any) of the statement
+ ** and/or current transaction is rolled back.
+ */
+ static void sqlite3HaltConstraint(Parse pParse, int onError, string p4, int p4type) {
+ Vdbe v = sqlite3GetVdbe(pParse);
+ if (onError == OE_Abort) {
+ sqlite3MayAbort(pParse);
+ }
+ sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
+ }
- static void sqlite3HaltConstraint( Parse pParse, int onError, byte[] p4, int p4type )
- {
- Vdbe v = sqlite3GetVdbe( pParse );
- if ( onError == OE_Abort )
- {
- sqlite3MayAbort( pParse );
- }
- sqlite3VdbeAddOp4( v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type );
- }
+ static void sqlite3HaltConstraint(Parse pParse, int onError, byte[] p4, int p4type) {
+ Vdbe v = sqlite3GetVdbe(pParse);
+ if (onError == OE_Abort) {
+ sqlite3MayAbort(pParse);
+ }
+ sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, onError, 0, p4, p4type);
+ }
- /*
- ** Check to see if pIndex uses the collating sequence pColl. Return
- ** true if it does and false if it does not.
- */
+ /*
+ ** Check to see if pIndex uses the collating sequence pColl. Return
+ ** true if it does and false if it does not.
+ */
#if !SQLITE_OMIT_REINDEX
- static bool collationMatch( string zColl, Index pIndex )
- {
- int i;
- Debug.Assert( zColl != null );
- for ( i = 0; i < pIndex.nColumn; i++ )
- {
- string z = pIndex.azColl[i];
- Debug.Assert( z != null );
- if ( z.Equals( zColl, StringComparison.OrdinalIgnoreCase ) )
- {
- return true;
+ static bool collationMatch(string zColl, Index pIndex) {
+ int i;
+ Debug.Assert(zColl != null);
+ for (i = 0; i < pIndex.nColumn; i++) {
+ string z = pIndex.azColl[i];
+ Debug.Assert(z != null);
+ if (z.Equals(zColl, StringComparison.OrdinalIgnoreCase)) {
+ return true;
+ }
+ }
+ return false;
}
- }
- return false;
- }
#endif
- /*
-** Recompute all indices of pTab that use the collating sequence pColl.
-** If pColl == null then recompute all indices of pTab.
-*/
+ /*
+ ** Recompute all indices of pTab that use the collating sequence pColl.
+ ** If pColl == null then recompute all indices of pTab.
+ */
#if !SQLITE_OMIT_REINDEX
- static void reindexTable( Parse pParse, Table pTab, string zColl )
- {
- Index pIndex; /* An index associated with pTab */
-
- for ( pIndex = pTab.pIndex; pIndex != null; pIndex = pIndex.pNext )
- {
- if ( zColl == null || collationMatch( zColl, pIndex ) )
- {
- int iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
- sqlite3BeginWriteOperation( pParse, 0, iDb );
- sqlite3RefillIndex( pParse, pIndex, -1 );
+ static void reindexTable(Parse pParse, Table pTab, string zColl) {
+ Index pIndex; /* An index associated with pTab */
+
+ for (pIndex = pTab.pIndex; pIndex != null; pIndex = pIndex.pNext) {
+ if (zColl == null || collationMatch(zColl, pIndex)) {
+ int iDb = sqlite3SchemaToIndex(pParse.db, pTab.pSchema);
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ sqlite3RefillIndex(pParse, pIndex, -1);
+ }
+ }
}
- }
- }
#endif
- /*
-** Recompute all indices of all tables in all databases where the
-** indices use the collating sequence pColl. If pColl == null then recompute
-** all indices everywhere.
-*/
+ /*
+ ** Recompute all indices of all tables in all databases where the
+ ** indices use the collating sequence pColl. If pColl == null then recompute
+ ** all indices everywhere.
+ */
#if !SQLITE_OMIT_REINDEX
- static void reindexDatabases( Parse pParse, string zColl )
- {
- Db pDb; /* A single database */
- int iDb; /* The database index number */
- sqlite3 db = pParse.db; /* The database connection */
- HashElem k; /* For looping over tables in pDb */
- Table pTab; /* A table in the database */
-
- Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) ); /* Needed for schema access */
- for ( iDb = 0; iDb < db.nDb; iDb++ )//, pDb++ )
- {
- pDb = db.aDb[iDb];
- Debug.Assert( pDb != null );
- for ( k = pDb.pSchema.tblHash.first; k != null; k = k.next ) //for ( k = sqliteHashFirst( pDb.pSchema.tblHash ) ; k != null ; k = sqliteHashNext( k ) )
- {
- pTab = (Table)k.data;// sqliteHashData( k );
- reindexTable( pParse, pTab, zColl );
+ static void reindexDatabases(Parse pParse, string zColl) {
+ Db pDb; /* A single database */
+ int iDb; /* The database index number */
+ sqlite3 db = pParse.db; /* The database connection */
+ HashElem k; /* For looping over tables in pDb */
+ Table pTab; /* A table in the database */
+
+ Debug.Assert(sqlite3BtreeHoldsAllMutexes(db)); /* Needed for schema access */
+ for (iDb = 0; iDb < db.nDb; iDb++)//, pDb++ )
+ {
+ pDb = db.aDb[iDb];
+ Debug.Assert(pDb != null);
+ for (k = pDb.pSchema.tblHash.first; k != null; k = k.next) //for ( k = sqliteHashFirst( pDb.pSchema.tblHash ) ; k != null ; k = sqliteHashNext( k ) )
+ {
+ pTab = (Table)k.data;// sqliteHashData( k );
+ reindexTable(pParse, pTab, zColl);
+ }
+ }
}
- }
- }
#endif
- /*
-** Generate code for the REINDEX command.
-**
-** REINDEX -- 1
-** REINDEX -- 2
-** REINDEX ?.? -- 3
-** REINDEX ?.? -- 4
-**
-** Form 1 causes all indices in all attached databases to be rebuilt.
-** Form 2 rebuilds all indices in all databases that use the named
-** collating function. Forms 3 and 4 rebuild the named index or all
-** indices associated with the named table.
-*/
+ /*
+ ** Generate code for the REINDEX command.
+ **
+ ** REINDEX -- 1
+ ** REINDEX -- 2
+ ** REINDEX ?.? -- 3
+ ** REINDEX ?.? -- 4
+ **
+ ** Form 1 causes all indices in all attached databases to be rebuilt.
+ ** Form 2 rebuilds all indices in all databases that use the named
+ ** collating function. Forms 3 and 4 rebuild the named index or all
+ ** indices associated with the named table.
+ */
#if !SQLITE_OMIT_REINDEX
- // OVERLOADS, so I don't need to rewrite parse.c
- static void sqlite3Reindex( Parse pParse, int null_2, int null_3 )
- {
- sqlite3Reindex( pParse, null, null );
- }
- static void sqlite3Reindex( Parse pParse, Token pName1, Token pName2 )
- {
- CollSeq pColl; /* Collating sequence to be reindexed, or NULL */
- string z; /* Name of a table or index */
- string zDb; /* Name of the database */
- Table pTab; /* A table in the database */
- Index pIndex; /* An index associated with pTab */
- int iDb; /* The database index number */
- sqlite3 db = pParse.db; /* The database connection */
- Token pObjName = new Token(); /* Name of the table or index to be reindexed */
-
- /* Read the database schema. If an error occurs, leave an error message
- ** and code in pParse and return NULL. */
- if ( SQLITE_OK != sqlite3ReadSchema( pParse ) )
- {
- return;
- }
-
- if ( pName1 == null )
- {
- reindexDatabases( pParse, null );
- return;
- }
- else if ( NEVER( pName2 == null ) || pName2.z == null || pName2.z.Length == 0 )
- {
- string zColl;
- Debug.Assert( pName1.z != null );
- zColl = sqlite3NameFromToken( pParse.db, pName1 );
- if ( zColl == null )
- return;
- pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 );
- if ( pColl != null )
- {
- reindexDatabases( pParse, zColl );
- sqlite3DbFree( db, ref zColl );
- return;
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static void sqlite3Reindex(Parse pParse, int null_2, int null_3) {
+ sqlite3Reindex(pParse, null, null);
+ }
+ static void sqlite3Reindex(Parse pParse, Token pName1, Token pName2) {
+ CollSeq pColl; /* Collating sequence to be reindexed, or NULL */
+ string z; /* Name of a table or index */
+ string zDb; /* Name of the database */
+ Table pTab; /* A table in the database */
+ Index pIndex; /* An index associated with pTab */
+ int iDb; /* The database index number */
+ sqlite3 db = pParse.db; /* The database connection */
+ Token pObjName = new Token(); /* Name of the table or index to be reindexed */
+
+ /* Read the database schema. If an error occurs, leave an error message
+ ** and code in pParse and return NULL. */
+ if (SQLITE_OK != sqlite3ReadSchema(pParse)) {
+ return;
+ }
+
+ if (pName1 == null) {
+ reindexDatabases(pParse, null);
+ return;
+ } else if (NEVER(pName2 == null) || pName2.z == null || pName2.z.Length == 0) {
+ string zColl;
+ Debug.Assert(pName1.z != null);
+ zColl = sqlite3NameFromToken(pParse.db, pName1);
+ if (zColl == null)
+ return;
+ pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
+ if (pColl != null) {
+ reindexDatabases(pParse, zColl);
+ sqlite3DbFree(db, ref zColl);
+ return;
+ }
+ sqlite3DbFree(db, ref zColl);
+ }
+ iDb = sqlite3TwoPartName(pParse, pName1, pName2, ref pObjName);
+ if (iDb < 0)
+ return;
+ z = sqlite3NameFromToken(db, pObjName);
+ if (z == null)
+ return;
+ zDb = db.aDb[iDb].zName;
+ pTab = sqlite3FindTable(db, z, zDb);
+ if (pTab != null) {
+ reindexTable(pParse, pTab, null);
+ sqlite3DbFree(db, ref z);
+ return;
+ }
+ pIndex = sqlite3FindIndex(db, z, zDb);
+ sqlite3DbFree(db, ref z);
+ if (pIndex != null) {
+ sqlite3BeginWriteOperation(pParse, 0, iDb);
+ sqlite3RefillIndex(pParse, pIndex, -1);
+ return;
+ }
+ sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
}
- sqlite3DbFree( db, ref zColl );
- }
- iDb = sqlite3TwoPartName( pParse, pName1, pName2, ref pObjName );
- if ( iDb < 0 )
- return;
- z = sqlite3NameFromToken( db, pObjName );
- if ( z == null )
- return;
- zDb = db.aDb[iDb].zName;
- pTab = sqlite3FindTable( db, z, zDb );
- if ( pTab != null )
- {
- reindexTable( pParse, pTab, null );
- sqlite3DbFree( db, ref z );
- return;
- }
- pIndex = sqlite3FindIndex( db, z, zDb );
- sqlite3DbFree( db, ref z );
- if ( pIndex != null )
- {
- sqlite3BeginWriteOperation( pParse, 0, iDb );
- sqlite3RefillIndex( pParse, pIndex, -1 );
- return;
- }
- sqlite3ErrorMsg( pParse, "unable to identify the object to be reindexed" );
- }
#endif
- /*
-** Return a dynamicly allocated KeyInfo structure that can be used
-** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
-**
-** If successful, a pointer to the new structure is returned. In this case
-** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
-** pointer. If an error occurs (out of memory or missing collation
-** sequence), NULL is returned and the state of pParse updated to reflect
-** the error.
-*/
- static KeyInfo sqlite3IndexKeyinfo( Parse pParse, Index pIdx )
- {
- int i;
- int nCol = pIdx.nColumn;
- //int nBytes = KeyInfo.Length + (nCol - 1) * CollSeq*.Length + nCol;
- sqlite3 db = pParse.db;
- KeyInfo pKey = new KeyInfo();// (KeyInfo)sqlite3DbMallocZero(db, nBytes);
-
- if ( pKey != null )
- {
- pKey.db = pParse.db;
- pKey.aSortOrder = new byte[nCol];
- pKey.aColl = new CollSeq[nCol];// (u8)&(pKey.aColl[nCol]);
- // Debug.Assert(pKey.aSortOrder[nCol] == (((u8)pKey)[nBytes]));
- for ( i = 0; i < nCol; i++ )
- {
- string zColl = pIdx.azColl[i];
- Debug.Assert( zColl != null );
- pKey.aColl[i] = sqlite3LocateCollSeq( pParse, zColl );
- pKey.aSortOrder[i] = pIdx.aSortOrder[i];
+ /*
+ ** Return a dynamicly allocated KeyInfo structure that can be used
+ ** with OP_OpenRead or OP_OpenWrite to access database index pIdx.
+ **
+ ** If successful, a pointer to the new structure is returned. In this case
+ ** the caller is responsible for calling sqlite3DbFree(db, ) on the returned
+ ** pointer. If an error occurs (out of memory or missing collation
+ ** sequence), NULL is returned and the state of pParse updated to reflect
+ ** the error.
+ */
+ static KeyInfo sqlite3IndexKeyinfo(Parse pParse, Index pIdx) {
+ int i;
+ int nCol = pIdx.nColumn;
+ //int nBytes = KeyInfo.Length + (nCol - 1) * CollSeq*.Length + nCol;
+ sqlite3 db = pParse.db;
+ KeyInfo pKey = new KeyInfo();// (KeyInfo)sqlite3DbMallocZero(db, nBytes);
+
+ if (pKey != null) {
+ pKey.db = pParse.db;
+ pKey.aSortOrder = new byte[nCol];
+ pKey.aColl = new CollSeq[nCol];// (u8)&(pKey.aColl[nCol]);
+ // Debug.Assert(pKey.aSortOrder[nCol] == (((u8)pKey)[nBytes]));
+ for (i = 0; i < nCol; i++) {
+ string zColl = pIdx.azColl[i];
+ Debug.Assert(zColl != null);
+ pKey.aColl[i] = sqlite3LocateCollSeq(pParse, zColl);
+ pKey.aSortOrder[i] = pIdx.aSortOrder[i];
+ }
+ pKey.nField = (u16)nCol;
+ }
+
+ if (pParse.nErr != 0) {
+ pKey = null;
+ sqlite3DbFree(db, ref pKey);
+ }
+ return pKey;
}
- pKey.nField = (u16)nCol;
- }
-
- if ( pParse.nErr != 0 )
- {
- pKey = null;
- sqlite3DbFree( db, ref pKey );
- }
- return pKey;
}
- }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/callback_c.cs b/Src/IronPython.SQLite/c#sqlite/callback_c.cs
index 914f86f22..a014b9d1c 100644
--- a/Src/IronPython.SQLite/c#sqlite/callback_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/callback_c.cs
@@ -1,57 +1,50 @@
using System;
using System.Diagnostics;
-using System.Text;
using i16 = System.Int16;
-using u8 = System.Byte;
using u16 = System.UInt16;
+using u8 = System.Byte;
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
-
- public partial class Sqlite3
- {
- /*
- ** 2005 May 23
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- **
- ** This file contains functions used to access the internal hash tables
- ** of user defined functions and collation sequences.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
- **
- *************************************************************************
- */
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2005 May 23
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ **
+ ** This file contains functions used to access the internal hash tables
+ ** of user defined functions and collation sequences.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
+ **
+ *************************************************************************
+ */
- //#include "sqliteInt.h"
+ //#include "sqliteInt.h"
- /*
- ** Invoke the 'collation needed' callback to request a collation sequence
- ** in the encoding enc of name zName, length nName.
- */
- static void callCollNeeded( sqlite3 db, int enc, string zName )
- {
- Debug.Assert( db.xCollNeeded == null || db.xCollNeeded16 == null );
- if ( db.xCollNeeded != null )
- {
- string zExternal = zName;// sqlite3DbStrDup(db, zName);
- if ( zExternal == null )
- return;
- db.xCollNeeded( db.pCollNeededArg, db, enc, zExternal );
- sqlite3DbFree( db, ref zExternal );
- }
+ /*
+ ** Invoke the 'collation needed' callback to request a collation sequence
+ ** in the encoding enc of name zName, length nName.
+ */
+ static void callCollNeeded(sqlite3 db, int enc, string zName) {
+ Debug.Assert(db.xCollNeeded == null || db.xCollNeeded16 == null);
+ if (db.xCollNeeded != null) {
+ string zExternal = zName;// sqlite3DbStrDup(db, zName);
+ if (zExternal == null)
+ return;
+ db.xCollNeeded(db.pCollNeededArg, db, enc, zExternal);
+ sqlite3DbFree(db, ref zExternal);
+ }
#if !SQLITE_OMIT_UTF16
if( db.xCollNeeded16!=null ){
string zExternal;
@@ -64,496 +57,445 @@ static void callCollNeeded( sqlite3 db, int enc, string zName )
sqlite3ValueFree(ref pTmp);
}
#endif
- }
-
- /*
- ** This routine is called if the collation factory fails to deliver a
- ** collation function in the best encoding but there may be other versions
- ** of this collation function (for other text encodings) available. Use one
- ** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if
- ** possible.
- */
- static int synthCollSeq( sqlite3 db, CollSeq pColl )
- {
- CollSeq pColl2;
- string z = pColl.zName;
- int i;
- byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
- for ( i = 0; i < 3; i++ )
- {
- pColl2 = sqlite3FindCollSeq( db, aEnc[i], z, 0 );
- if ( pColl2.xCmp != null )
- {
- pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq));
- pColl.xDel = null; /* Do not copy the destructor */
- return SQLITE_OK;
}
- }
- return SQLITE_ERROR;
- }
- /*
- ** This function is responsible for invoking the collation factory callback
- ** or substituting a collation sequence of a different encoding when the
- ** requested collation sequence is not available in the desired encoding.
- **
- ** If it is not NULL, then pColl must point to the database native encoding
- ** collation sequence with name zName, length nName.
- **
- ** The return value is either the collation sequence to be used in database
- ** db for collation type name zName, length nName, or NULL, if no collation
- ** sequence can be found.
- **
- ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
- */
- static CollSeq sqlite3GetCollSeq(
- sqlite3 db, /* The database connection */
- u8 enc, /* The desired encoding for the collating sequence */
- CollSeq pColl, /* Collating sequence with native encoding, or NULL */
- string zName /* Collating sequence name */
- )
- {
- CollSeq p;
+ /*
+ ** This routine is called if the collation factory fails to deliver a
+ ** collation function in the best encoding but there may be other versions
+ ** of this collation function (for other text encodings) available. Use one
+ ** of these instead if they exist. Avoid a UTF-8 <. UTF-16 conversion if
+ ** possible.
+ */
+ static int synthCollSeq(sqlite3 db, CollSeq pColl) {
+ CollSeq pColl2;
+ string z = pColl.zName;
+ int i;
+ byte[] aEnc = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
+ for (i = 0; i < 3; i++) {
+ pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
+ if (pColl2.xCmp != null) {
+ pColl = pColl2.Copy(); //memcpy(pColl, pColl2, sizeof(CollSeq));
+ pColl.xDel = null; /* Do not copy the destructor */
+ return SQLITE_OK;
+ }
+ }
+ return SQLITE_ERROR;
+ }
- p = pColl;
- if ( p == null )
- {
- p = sqlite3FindCollSeq( db, enc, zName, 0 );
- }
- if ( p == null || p.xCmp == null )
- {
- /* No collation sequence of this type for this encoding is registered.
- ** Call the collation factory to see if it can supply us with one.
+ /*
+ ** This function is responsible for invoking the collation factory callback
+ ** or substituting a collation sequence of a different encoding when the
+ ** requested collation sequence is not available in the desired encoding.
+ **
+ ** If it is not NULL, then pColl must point to the database native encoding
+ ** collation sequence with name zName, length nName.
+ **
+ ** The return value is either the collation sequence to be used in database
+ ** db for collation type name zName, length nName, or NULL, if no collation
+ ** sequence can be found.
+ **
+ ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
*/
- callCollNeeded( db, enc, zName );
- p = sqlite3FindCollSeq( db, enc, zName, 0 );
- }
- if ( p != null && p.xCmp == null && synthCollSeq( db, p ) != 0 )
- {
- p = null;
- }
- Debug.Assert( p == null || p.xCmp != null );
- return p;
- }
+ static CollSeq sqlite3GetCollSeq(
+ sqlite3 db, /* The database connection */
+ u8 enc, /* The desired encoding for the collating sequence */
+ CollSeq pColl, /* Collating sequence with native encoding, or NULL */
+ string zName /* Collating sequence name */
+ ) {
+ CollSeq p;
- /*
- ** This routine is called on a collation sequence before it is used to
- ** check that it is defined. An undefined collation sequence exists when
- ** a database is loaded that contains references to collation sequences
- ** that have not been defined by sqlite3_create_collation() etc.
- **
- ** If required, this routine calls the 'collation needed' callback to
- ** request a definition of the collating sequence. If this doesn't work,
- ** an equivalent collating sequence that uses a text encoding different
- ** from the main database is substituted, if one is available.
- */
- static int sqlite3CheckCollSeq( Parse pParse, CollSeq pColl )
- {
- if ( pColl != null )
- {
- string zName = pColl.zName;
- sqlite3 db = pParse.db;
- CollSeq p = sqlite3GetCollSeq( db, ENC( db ), pColl, zName );
- if ( null == p )
- {
- sqlite3ErrorMsg( pParse, "no such collation sequence: %s", zName );
- pParse.nErr++;
- return SQLITE_ERROR;
- }
- //
- //Debug.Assert(p == pColl);
- if ( p != pColl ) // Had to lookup appropriate sequence
- {
- pColl.enc = p.enc;
- pColl.pUser = p.pUser;
- pColl.type = p.type;
- pColl.xCmp = p.xCmp;
- pColl.xDel = p.xDel;
+ p = pColl;
+ if (p == null) {
+ p = sqlite3FindCollSeq(db, enc, zName, 0);
+ }
+ if (p == null || p.xCmp == null) {
+ /* No collation sequence of this type for this encoding is registered.
+ ** Call the collation factory to see if it can supply us with one.
+ */
+ callCollNeeded(db, enc, zName);
+ p = sqlite3FindCollSeq(db, enc, zName, 0);
+ }
+ if (p != null && p.xCmp == null && synthCollSeq(db, p) != 0) {
+ p = null;
+ }
+ Debug.Assert(p == null || p.xCmp != null);
+ return p;
}
- }
- return SQLITE_OK;
- }
-
+ /*
+ ** This routine is called on a collation sequence before it is used to
+ ** check that it is defined. An undefined collation sequence exists when
+ ** a database is loaded that contains references to collation sequences
+ ** that have not been defined by sqlite3_create_collation() etc.
+ **
+ ** If required, this routine calls the 'collation needed' callback to
+ ** request a definition of the collating sequence. If this doesn't work,
+ ** an equivalent collating sequence that uses a text encoding different
+ ** from the main database is substituted, if one is available.
+ */
+ static int sqlite3CheckCollSeq(Parse pParse, CollSeq pColl) {
+ if (pColl != null) {
+ string zName = pColl.zName;
+ sqlite3 db = pParse.db;
+ CollSeq p = sqlite3GetCollSeq(db, ENC(db), pColl, zName);
+ if (null == p) {
+ sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
+ pParse.nErr++;
+ return SQLITE_ERROR;
+ }
+ //
+ //Debug.Assert(p == pColl);
+ if (p != pColl) // Had to lookup appropriate sequence
+ {
+ pColl.enc = p.enc;
+ pColl.pUser = p.pUser;
+ pColl.type = p.type;
+ pColl.xCmp = p.xCmp;
+ pColl.xDel = p.xDel;
+ }
+ }
+ return SQLITE_OK;
+ }
- /*
- ** Locate and return an entry from the db.aCollSeq hash table. If the entry
- ** specified by zName and nName is not found and parameter 'create' is
- ** true, then create a new entry. Otherwise return NULL.
- **
- ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
- ** array of three CollSeq structures. The first is the collation sequence
- ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
- **
- ** Stored immediately after the three collation sequences is a copy of
- ** the collation sequence name. A pointer to this string is stored in
- ** each collation sequence structure.
- */
- static CollSeq[] findCollSeqEntry(
- sqlite3 db, /* Database connection */
- string zName, /* Name of the collating sequence */
- int create /* Create a new entry if true */
- )
- {
- CollSeq[] pColl;
- int nName = sqlite3Strlen30( zName );
- pColl = sqlite3HashFind( db.aCollSeq, zName, nName, (CollSeq[])null );
- if ( ( null == pColl ) && create != 0 )
- {
- pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
- if ( pColl != null )
- {
- CollSeq pDel = null;
- pColl[0] = new CollSeq();
- pColl[0].zName = zName;
- pColl[0].enc = SQLITE_UTF8;
- pColl[1] = new CollSeq();
- pColl[1].zName = zName;
- pColl[1].enc = SQLITE_UTF16LE;
- pColl[2] = new CollSeq();
- pColl[2].zName = zName;
- pColl[2].enc = SQLITE_UTF16BE;
- //memcpy(pColl[0].zName, zName, nName);
- //pColl[0].zName[nName] = 0;
- CollSeq[] pDelArray = sqlite3HashInsert( ref db.aCollSeq, pColl[0].zName, nName, pColl );
- if ( pDelArray != null )
- pDel = pDelArray[0];
- /* If a malloc() failure occurred in sqlite3HashInsert(), it will
- ** return the pColl pointer to be deleted (because it wasn't added
- ** to the hash table).
- */
- Debug.Assert( pDel == null || pDel == pColl[0] );
- if ( pDel != null )
- {
- //// db.mallocFailed = 1;
- pDel = null; //was sqlite3DbFree(db,ref pDel);
- pColl = null;
- }
- }
- }
- return pColl;
- }
- /*
- ** Parameter zName points to a UTF-8 encoded string nName bytes long.
- ** Return the CollSeq* pointer for the collation sequence named zName
- ** for the encoding 'enc' from the database 'db'.
- **
- ** If the entry specified is not found and 'create' is true, then create a
- ** new entry. Otherwise return NULL.
- **
- ** A separate function sqlite3LocateCollSeq() is a wrapper around
- ** this routine. sqlite3LocateCollSeq() invokes the collation factory
- ** if necessary and generates an error message if the collating sequence
- ** cannot be found.
- **
- ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
- */
- static CollSeq sqlite3FindCollSeq(
- sqlite3 db,
- u8 enc,
- string zName,
- u8 create
- )
- {
- CollSeq[] pColl;
- if ( zName != null )
- {
- pColl = findCollSeqEntry( db, zName, create );
- }
- else
- {
- pColl = new CollSeq[enc];
- pColl[enc - 1] = db.pDfltColl;
- }
- Debug.Assert( SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3 );
- Debug.Assert( enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE );
- if ( pColl != null )
- {
- enc -= 1; // if (pColl != null) pColl += enc - 1;
- return pColl[enc];
- }
- else
- return null;
- }
+ /*
+ ** Locate and return an entry from the db.aCollSeq hash table. If the entry
+ ** specified by zName and nName is not found and parameter 'create' is
+ ** true, then create a new entry. Otherwise return NULL.
+ **
+ ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
+ ** array of three CollSeq structures. The first is the collation sequence
+ ** prefferred for UTF-8, the second UTF-16le, and the third UTF-16be.
+ **
+ ** Stored immediately after the three collation sequences is a copy of
+ ** the collation sequence name. A pointer to this string is stored in
+ ** each collation sequence structure.
+ */
+ static CollSeq[] findCollSeqEntry(
+ sqlite3 db, /* Database connection */
+ string zName, /* Name of the collating sequence */
+ int create /* Create a new entry if true */
+ ) {
+ CollSeq[] pColl;
+ int nName = sqlite3Strlen30(zName);
+ pColl = sqlite3HashFind(db.aCollSeq, zName, nName, (CollSeq[])null);
- /* During the search for the best function definition, this procedure
- ** is called to test how well the function passed as the first argument
- ** matches the request for a function with nArg arguments in a system
- ** that uses encoding enc. The value returned indicates how well the
- ** request is matched. A higher value indicates a better match.
- **
- ** The returned value is always between 0 and 6, as follows:
- **
- ** 0: Not a match, or if nArg<0 and the function is has no implementation.
- ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
- ** encoding is requested, or vice versa.
- ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
- ** requested, or vice versa.
- ** 3: A variable arguments function using the same text encoding.
- ** 4: A function with the exact number of arguments requested that
- ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
- ** 5: A function with the exact number of arguments requested that
- ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
- ** 6: An exact match.
- **
- */
- static int matchQuality( FuncDef p, int nArg, int enc )
- {
- int match = 0;
- if ( p.nArg == -1 || p.nArg == nArg
- || ( nArg == -1 && ( p.xFunc != null || p.xStep != null ) )
- )
- {
- match = 1;
- if ( p.nArg == nArg || nArg == -1 )
- {
- match = 4;
+ if ((null == pColl) && create != 0) {
+ pColl = new CollSeq[3]; //sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1 );
+ if (pColl != null) {
+ CollSeq pDel = null;
+ pColl[0] = new CollSeq();
+ pColl[0].zName = zName;
+ pColl[0].enc = SQLITE_UTF8;
+ pColl[1] = new CollSeq();
+ pColl[1].zName = zName;
+ pColl[1].enc = SQLITE_UTF16LE;
+ pColl[2] = new CollSeq();
+ pColl[2].zName = zName;
+ pColl[2].enc = SQLITE_UTF16BE;
+ //memcpy(pColl[0].zName, zName, nName);
+ //pColl[0].zName[nName] = 0;
+ CollSeq[] pDelArray = sqlite3HashInsert(ref db.aCollSeq, pColl[0].zName, nName, pColl);
+ if (pDelArray != null)
+ pDel = pDelArray[0];
+ /* If a malloc() failure occurred in sqlite3HashInsert(), it will
+ ** return the pColl pointer to be deleted (because it wasn't added
+ ** to the hash table).
+ */
+ Debug.Assert(pDel == null || pDel == pColl[0]);
+ if (pDel != null) {
+ //// db.mallocFailed = 1;
+ pDel = null; //was sqlite3DbFree(db,ref pDel);
+ pColl = null;
+ }
+ }
+ }
+ return pColl;
}
- if ( enc == p.iPrefEnc )
- {
- match += 2;
+
+ /*
+ ** Parameter zName points to a UTF-8 encoded string nName bytes long.
+ ** Return the CollSeq* pointer for the collation sequence named zName
+ ** for the encoding 'enc' from the database 'db'.
+ **
+ ** If the entry specified is not found and 'create' is true, then create a
+ ** new entry. Otherwise return NULL.
+ **
+ ** A separate function sqlite3LocateCollSeq() is a wrapper around
+ ** this routine. sqlite3LocateCollSeq() invokes the collation factory
+ ** if necessary and generates an error message if the collating sequence
+ ** cannot be found.
+ **
+ ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
+ */
+ static CollSeq sqlite3FindCollSeq(
+ sqlite3 db,
+ u8 enc,
+ string zName,
+ u8 create
+ ) {
+ CollSeq[] pColl;
+ if (zName != null) {
+ pColl = findCollSeqEntry(db, zName, create);
+ } else {
+ pColl = new CollSeq[enc];
+ pColl[enc - 1] = db.pDfltColl;
+ }
+ Debug.Assert(SQLITE_UTF8 == 1 && SQLITE_UTF16LE == 2 && SQLITE_UTF16BE == 3);
+ Debug.Assert(enc >= SQLITE_UTF8 && enc <= SQLITE_UTF16BE);
+ if (pColl != null) {
+ enc -= 1; // if (pColl != null) pColl += enc - 1;
+ return pColl[enc];
+ } else
+ return null;
}
- else if ( ( enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE ) ||
- ( enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE ) )
- {
- match += 1;
+
+ /* During the search for the best function definition, this procedure
+ ** is called to test how well the function passed as the first argument
+ ** matches the request for a function with nArg arguments in a system
+ ** that uses encoding enc. The value returned indicates how well the
+ ** request is matched. A higher value indicates a better match.
+ **
+ ** The returned value is always between 0 and 6, as follows:
+ **
+ ** 0: Not a match, or if nArg<0 and the function is has no implementation.
+ ** 1: A variable arguments function that prefers UTF-8 when a UTF-16
+ ** encoding is requested, or vice versa.
+ ** 2: A variable arguments function that uses UTF-16BE when UTF-16LE is
+ ** requested, or vice versa.
+ ** 3: A variable arguments function using the same text encoding.
+ ** 4: A function with the exact number of arguments requested that
+ ** prefers UTF-8 when a UTF-16 encoding is requested, or vice versa.
+ ** 5: A function with the exact number of arguments requested that
+ ** prefers UTF-16LE when UTF-16BE is requested, or vice versa.
+ ** 6: An exact match.
+ **
+ */
+ static int matchQuality(FuncDef p, int nArg, int enc) {
+ int match = 0;
+ if (p.nArg == -1 || p.nArg == nArg
+ || (nArg == -1 && (p.xFunc != null || p.xStep != null))
+ ) {
+ match = 1;
+ if (p.nArg == nArg || nArg == -1) {
+ match = 4;
+ }
+ if (enc == p.iPrefEnc) {
+ match += 2;
+ } else if ((enc == SQLITE_UTF16LE && p.iPrefEnc == SQLITE_UTF16BE) ||
+ (enc == SQLITE_UTF16BE && p.iPrefEnc == SQLITE_UTF16LE)) {
+ match += 1;
+ }
+ }
+ return match;
}
- }
- return match;
- }
- /*
- ** Search a FuncDefHash for a function with the given name. Return
- ** a pointer to the matching FuncDef if found, or 0 if there is no match.
- */
- static FuncDef functionSearch(
- FuncDefHash pHash, /* Hash table to search */
- int h, /* Hash of the name */
- string zFunc, /* Name of function */
- int nFunc /* Number of bytes in zFunc */
- )
- {
- FuncDef p;
- for ( p = pHash.a[h]; p != null; p = p.pHash )
- {
- if ( p.zName.Length == nFunc && p.zName.StartsWith( zFunc, StringComparison.OrdinalIgnoreCase ) )
- {
- return p;
+ /*
+ ** Search a FuncDefHash for a function with the given name. Return
+ ** a pointer to the matching FuncDef if found, or 0 if there is no match.
+ */
+ static FuncDef functionSearch(
+ FuncDefHash pHash, /* Hash table to search */
+ int h, /* Hash of the name */
+ string zFunc, /* Name of function */
+ int nFunc /* Number of bytes in zFunc */
+ ) {
+ FuncDef p;
+ for (p = pHash.a[h]; p != null; p = p.pHash) {
+ if (p.zName.Length == nFunc && p.zName.StartsWith(zFunc, StringComparison.OrdinalIgnoreCase)) {
+ return p;
+ }
+ }
+ return null;
}
- }
- return null;
- }
- /*
- ** Insert a new FuncDef into a FuncDefHash hash table.
- */
- static void sqlite3FuncDefInsert(
- FuncDefHash pHash, /* The hash table into which to insert */
- FuncDef pDef /* The function definition to insert */
- )
- {
- FuncDef pOther;
- int nName = sqlite3Strlen30( pDef.zName );
- u8 c1 = (u8)pDef.zName[0];
- int h = ( sqlite3UpperToLower[c1] + nName ) % ArraySize( pHash.a );
- pOther = functionSearch( pHash, h, pDef.zName, nName );
- if ( pOther != null )
- {
- Debug.Assert( pOther != pDef && pOther.pNext != pDef );
- pDef.pNext = pOther.pNext;
- pOther.pNext = pDef;
- }
- else
- {
- pDef.pNext = null;
- pDef.pHash = pHash.a[h];
- pHash.a[h] = pDef;
- }
- }
+ /*
+ ** Insert a new FuncDef into a FuncDefHash hash table.
+ */
+ static void sqlite3FuncDefInsert(
+ FuncDefHash pHash, /* The hash table into which to insert */
+ FuncDef pDef /* The function definition to insert */
+ ) {
+ FuncDef pOther;
+ int nName = sqlite3Strlen30(pDef.zName);
+ u8 c1 = (u8)pDef.zName[0];
+ int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash.a);
+ pOther = functionSearch(pHash, h, pDef.zName, nName);
+ if (pOther != null) {
+ Debug.Assert(pOther != pDef && pOther.pNext != pDef);
+ pDef.pNext = pOther.pNext;
+ pOther.pNext = pDef;
+ } else {
+ pDef.pNext = null;
+ pDef.pHash = pHash.a[h];
+ pHash.a[h] = pDef;
+ }
+ }
- /*
- ** Locate a user function given a name, a number of arguments and a flag
- ** indicating whether the function prefers UTF-16 over UTF-8. Return a
- ** pointer to the FuncDef structure that defines that function, or return
- ** NULL if the function does not exist.
- **
- ** If the createFlag argument is true, then a new (blank) FuncDef
- ** structure is created and liked into the "db" structure if a
- ** no matching function previously existed. When createFlag is true
- ** and the nArg parameter is -1, then only a function that accepts
- ** any number of arguments will be returned.
- **
- ** If createFlag is false and nArg is -1, then the first valid
- ** function found is returned. A function is valid if either xFunc
- ** or xStep is non-zero.
- **
- ** If createFlag is false, then a function with the required name and
- ** number of arguments may be returned even if the eTextRep flag does not
- ** match that requested.
- */
+ /*
+ ** Locate a user function given a name, a number of arguments and a flag
+ ** indicating whether the function prefers UTF-16 over UTF-8. Return a
+ ** pointer to the FuncDef structure that defines that function, or return
+ ** NULL if the function does not exist.
+ **
+ ** If the createFlag argument is true, then a new (blank) FuncDef
+ ** structure is created and liked into the "db" structure if a
+ ** no matching function previously existed. When createFlag is true
+ ** and the nArg parameter is -1, then only a function that accepts
+ ** any number of arguments will be returned.
+ **
+ ** If createFlag is false and nArg is -1, then the first valid
+ ** function found is returned. A function is valid if either xFunc
+ ** or xStep is non-zero.
+ **
+ ** If createFlag is false, then a function with the required name and
+ ** number of arguments may be returned even if the eTextRep flag does not
+ ** match that requested.
+ */
- static FuncDef sqlite3FindFunction(
- sqlite3 db, /* An open database */
- string zName, /* Name of the function. Not null-terminated */
- int nName, /* Number of characters in the name */
- int nArg, /* Number of arguments. -1 means any number */
- u8 enc, /* Preferred text encoding */
- u8 createFlag /* Create new entry if true and does not otherwise exist */
- )
- {
- FuncDef p; /* Iterator variable */
- FuncDef pBest = null; /* Best match found so far */
- int bestScore = 0;
- int h; /* Hash value */
+ static FuncDef sqlite3FindFunction(
+ sqlite3 db, /* An open database */
+ string zName, /* Name of the function. Not null-terminated */
+ int nName, /* Number of characters in the name */
+ int nArg, /* Number of arguments. -1 means any number */
+ u8 enc, /* Preferred text encoding */
+ u8 createFlag /* Create new entry if true and does not otherwise exist */
+ ) {
+ FuncDef p; /* Iterator variable */
+ FuncDef pBest = null; /* Best match found so far */
+ int bestScore = 0;
+ int h; /* Hash value */
- Debug.Assert( enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE );
- h = ( sqlite3UpperToLower[(u8)zName[0]] + nName ) % ArraySize( db.aFunc.a );
+ Debug.Assert(enc == SQLITE_UTF8 || enc == SQLITE_UTF16LE || enc == SQLITE_UTF16BE);
+ h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db.aFunc.a);
- /* First search for a match amongst the application-defined functions.
- */
- p = functionSearch( db.aFunc, h, zName, nName );
- while ( p != null )
- {
- int score = matchQuality( p, nArg, enc );
- if ( score > bestScore )
- {
- pBest = p;
- bestScore = score;
+ /* First search for a match amongst the application-defined functions.
+ */
+ p = functionSearch(db.aFunc, h, zName, nName);
+ while (p != null) {
+ int score = matchQuality(p, nArg, enc);
+ if (score > bestScore) {
+ pBest = p;
+ bestScore = score;
- }
- p = p.pNext;
- }
+ }
+ p = p.pNext;
+ }
- /* If no match is found, search the built-in functions.
- **
- ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
- ** functions even if a prior app-defined function was found. And give
- ** priority to built-in functions.
- **
- ** Except, if createFlag is true, that means that we are trying to
- ** install a new function. Whatever FuncDef structure is returned it will
- ** have fields overwritten with new information appropriate for the
- ** new function. But the FuncDefs for built-in functions are read-only.
- ** So we must not search for built-ins when creating a new function.
- */
- if ( 0 == createFlag && ( pBest == null || ( db.flags & SQLITE_PreferBuiltin ) != 0 ) )
- {
+ /* If no match is found, search the built-in functions.
+ **
+ ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
+ ** functions even if a prior app-defined function was found. And give
+ ** priority to built-in functions.
+ **
+ ** Except, if createFlag is true, that means that we are trying to
+ ** install a new function. Whatever FuncDef structure is returned it will
+ ** have fields overwritten with new information appropriate for the
+ ** new function. But the FuncDefs for built-in functions are read-only.
+ ** So we must not search for built-ins when creating a new function.
+ */
+ if (0 == createFlag && (pBest == null || (db.flags & SQLITE_PreferBuiltin) != 0)) {
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions );
#else
- FuncDefHash pHash = sqlite3GlobalFunctions;
+ FuncDefHash pHash = sqlite3GlobalFunctions;
#endif
- bestScore = 0;
- p = functionSearch( pHash, h, zName, nName );
- while ( p != null )
- {
- int score = matchQuality( p, nArg, enc );
- if ( score > bestScore )
- {
- pBest = p;
- bestScore = score;
- }
- p = p.pNext;
- }
- }
+ bestScore = 0;
+ p = functionSearch(pHash, h, zName, nName);
+ while (p != null) {
+ int score = matchQuality(p, nArg, enc);
+ if (score > bestScore) {
+ pBest = p;
+ bestScore = score;
+ }
+ p = p.pNext;
+ }
+ }
- /* If the createFlag parameter is true and the search did not reveal an
- ** exact match for the name, number of arguments and encoding, then add a
- ** new entry to the hash table and return it.
- */
- if ( createFlag != 0 && ( bestScore < 6 || pBest.nArg != nArg ) &&
- ( pBest = new FuncDef() ) != null )
- { //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
- //pBest.zName = (char *)&pBest[1];
- pBest.nArg = (i16)nArg;
- pBest.iPrefEnc = enc;
- pBest.zName = zName; //memcpy(pBest.zName, zName, nName);
- //pBest.zName[nName] = 0;
- sqlite3FuncDefInsert( db.aFunc, pBest );
- }
+ /* If the createFlag parameter is true and the search did not reveal an
+ ** exact match for the name, number of arguments and encoding, then add a
+ ** new entry to the hash table and return it.
+ */
+ if (createFlag != 0 && (bestScore < 6 || pBest.nArg != nArg) &&
+ (pBest = new FuncDef()) != null) { //sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
+ //pBest.zName = (char *)&pBest[1];
+ pBest.nArg = (i16)nArg;
+ pBest.iPrefEnc = enc;
+ pBest.zName = zName; //memcpy(pBest.zName, zName, nName);
+ //pBest.zName[nName] = 0;
+ sqlite3FuncDefInsert(db.aFunc, pBest);
+ }
- if ( pBest != null && ( pBest.xStep != null || pBest.xFunc != null || createFlag != 0 ) )
- {
- return pBest;
- }
- return null;
- }
+ if (pBest != null && (pBest.xStep != null || pBest.xFunc != null || createFlag != 0)) {
+ return pBest;
+ }
+ return null;
+ }
- /*
- ** Free all resources held by the schema structure. The void* argument points
- ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
- ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
- ** of the schema hash tables).
- **
- ** The Schema.cache_size variable is not cleared.
- */
- static void sqlite3SchemaClear( Schema p )
- {
- Hash temp1;
- Hash temp2;
- HashElem pElem;
- Schema pSchema = p;
+ /*
+ ** Free all resources held by the schema structure. The void* argument points
+ ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
+ ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
+ ** of the schema hash tables).
+ **
+ ** The Schema.cache_size variable is not cleared.
+ */
+ static void sqlite3SchemaClear(Schema p) {
+ Hash temp1;
+ Hash temp2;
+ HashElem pElem;
+ Schema pSchema = p;
- temp1 = pSchema.tblHash;
- temp2 = pSchema.trigHash;
- sqlite3HashInit( pSchema.trigHash );
- sqlite3HashClear( pSchema.idxHash );
- for ( pElem = sqliteHashFirst( temp2 ); pElem != null; pElem = sqliteHashNext( pElem ) )
- {
- Trigger pTrigger = (Trigger)sqliteHashData( pElem );
- sqlite3DeleteTrigger( null, ref pTrigger );
- }
- sqlite3HashClear( temp2 );
- sqlite3HashInit( pSchema.trigHash );
- for ( pElem = temp1.first; pElem != null; pElem = pElem.next )//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem))
- {
- Table pTab = (Table)pElem.data; //sqliteHashData(pElem);
- sqlite3DeleteTable( null, ref pTab );
- }
- sqlite3HashClear( temp1 );
- sqlite3HashClear( pSchema.fkeyHash );
- pSchema.pSeqTab = null;
- if ( ( pSchema.flags & DB_SchemaLoaded ) != 0 )
- {
- pSchema.iGeneration++;
- pSchema.flags = (u16)( pSchema.flags & ( ~DB_SchemaLoaded ) );
- }
- p.Clear();
- }
+ temp1 = pSchema.tblHash;
+ temp2 = pSchema.trigHash;
+ sqlite3HashInit(pSchema.trigHash);
+ sqlite3HashClear(pSchema.idxHash);
+ for (pElem = sqliteHashFirst(temp2); pElem != null; pElem = sqliteHashNext(pElem)) {
+ Trigger pTrigger = (Trigger)sqliteHashData(pElem);
+ sqlite3DeleteTrigger(null, ref pTrigger);
+ }
+ sqlite3HashClear(temp2);
+ sqlite3HashInit(pSchema.trigHash);
+ for (pElem = temp1.first; pElem != null; pElem = pElem.next)//sqliteHashFirst(&temp1); pElem; pElem = sqliteHashNext(pElem))
+ {
+ Table pTab = (Table)pElem.data; //sqliteHashData(pElem);
+ sqlite3DeleteTable(null, ref pTab);
+ }
+ sqlite3HashClear(temp1);
+ sqlite3HashClear(pSchema.fkeyHash);
+ pSchema.pSeqTab = null;
+ if ((pSchema.flags & DB_SchemaLoaded) != 0) {
+ pSchema.iGeneration++;
+ pSchema.flags = (u16)(pSchema.flags & (~DB_SchemaLoaded));
+ }
+ p.Clear();
+ }
- /*
- ** Find and return the schema associated with a BTree. Create
- ** a new one if necessary.
- */
- static Schema sqlite3SchemaGet( sqlite3 db, Btree pBt )
- {
- Schema p;
- if ( pBt != null )
- {
- p = sqlite3BtreeSchema( pBt, -1, (dxFreeSchema)sqlite3SchemaClear );//Schema.Length, sqlite3SchemaFree);
- }
- else
- {
- p = new Schema(); // (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
- }
- if ( p == null )
- {
- //// db.mallocFailed = 1;
- }
- else if ( 0 == p.file_format )
- {
- sqlite3HashInit( p.tblHash );
- sqlite3HashInit( p.idxHash );
- sqlite3HashInit( p.trigHash );
- sqlite3HashInit( p.fkeyHash );
- p.enc = SQLITE_UTF8;
- }
- return p;
+ /*
+ ** Find and return the schema associated with a BTree. Create
+ ** a new one if necessary.
+ */
+ static Schema sqlite3SchemaGet(sqlite3 db, Btree pBt) {
+ Schema p;
+ if (pBt != null) {
+ p = sqlite3BtreeSchema(pBt, -1, (dxFreeSchema)sqlite3SchemaClear);//Schema.Length, sqlite3SchemaFree);
+ } else {
+ p = new Schema(); // (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
+ }
+ if (p == null) {
+ //// db.mallocFailed = 1;
+ } else if (0 == p.file_format) {
+ sqlite3HashInit(p.tblHash);
+ sqlite3HashInit(p.idxHash);
+ sqlite3HashInit(p.trigHash);
+ sqlite3HashInit(p.fkeyHash);
+ p.enc = SQLITE_UTF8;
+ }
+ return p;
+ }
}
- }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/complete_c.cs b/Src/IronPython.SQLite/c#sqlite/complete_c.cs
index e231fa9f4..c1556e9d2 100644
--- a/Src/IronPython.SQLite/c#sqlite/complete_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/complete_c.cs
@@ -1,137 +1,131 @@
-using System.Diagnostics;
+namespace Community.CsharpSqlite {
-namespace Community.CsharpSqlite
-{
+ using u8 = System.Byte;
- using u8 = System.Byte;
-
- public partial class Sqlite3
- {
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** An tokenizer for SQL
- **
- ** This file contains C code that implements the sqlite3_complete() API.
- ** This code used to be part of the tokenizer.c source file. But by
- ** separating it out, the code will be automatically omitted from
- ** static links that do not use it.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** An tokenizer for SQL
+ **
+ ** This file contains C code that implements the sqlite3_complete() API.
+ ** This code used to be part of the tokenizer.c source file. But by
+ ** separating it out, the code will be automatically omitted from
+ ** static links that do not use it.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
#if !SQLITE_OMIT_COMPLETE
- /*
-** This is defined in tokenize.c. We just have to import the definition.
-*/
+ /*
+ ** This is defined in tokenize.c. We just have to import the definition.
+ */
#if !SQLITE_AMALGAMATION
-#if SQLITE_ASCII
- //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
- static bool IdChar( u8 C )
- {
- return ( sqlite3CtypeMap[(char)C] & 0x46 ) != 0;
- }
+#if SQLITE_ASCII
+ //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
+ static bool IdChar(u8 C) {
+ return (sqlite3CtypeMap[(char)C] & 0x46) != 0;
+ }
#endif
-//#if SQLITE_EBCDIC
-//extern const char sqlite3IsEbcdicIdChar[];
-//#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
-//#endif
+ //#if SQLITE_EBCDIC
+ //extern const char sqlite3IsEbcdicIdChar[];
+ //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
+ //#endif
#endif // * SQLITE_AMALGAMATION */
- /*
-** Token types used by the sqlite3_complete() routine. See the header
-** comments on that procedure for additional information.
-*/
- const int tkSEMI = 0;
- const int tkWS = 1;
- const int tkOTHER = 2;
+ /*
+ ** Token types used by the sqlite3_complete() routine. See the header
+ ** comments on that procedure for additional information.
+ */
+ const int tkSEMI = 0;
+ const int tkWS = 1;
+ const int tkOTHER = 2;
#if !SQLITE_OMIT_TRIGGER
- const int tkEXPLAIN = 3;
- const int tkCREATE = 4;
- const int tkTEMP = 5;
- const int tkTRIGGER = 6;
- const int tkEND = 7;
+ const int tkEXPLAIN = 3;
+ const int tkCREATE = 4;
+ const int tkTEMP = 5;
+ const int tkTRIGGER = 6;
+ const int tkEND = 7;
#endif
- /*
-** Return TRUE if the given SQL string ends in a semicolon.
-**
-** Special handling is require for CREATE TRIGGER statements.
-** Whenever the CREATE TRIGGER keywords are seen, the statement
-** must end with ";END;".
-**
-** This implementation uses a state machine with 8 states:
-**
-** (0) INVALID We have not yet seen a non-whitespace character.
-**
-** (1) START At the beginning or end of an SQL statement. This routine
-** returns 1 if it ends in the START state and 0 if it ends
-** in any other state.
-**
-** (2) NORMAL We are in the middle of statement which ends with a single
-** semicolon.
-**
-** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
-** a statement.
-**
-** (4) CREATE The keyword CREATE has been seen at the beginning of a
-** statement, possibly preceeded by EXPLAIN and/or followed by
-** TEMP or TEMPORARY
-**
-** (5) TRIGGER We are in the middle of a trigger definition that must be
-** ended by a semicolon, the keyword END, and another semicolon.
-**
-** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
-** the end of a trigger definition.
-**
-** (7) END We've seen the ";END" of the ";END;" that occurs at the end
-** of a trigger difinition.
-**
-** Transitions between states above are determined by tokens extracted
-** from the input. The following tokens are significant:
-**
-** (0) tkSEMI A semicolon.
-** (1) tkWS Whitespace.
-** (2) tkOTHER Any other SQL token.
-** (3) tkEXPLAIN The "explain" keyword.
-** (4) tkCREATE The "create" keyword.
-** (5) tkTEMP The "temp" or "temporary" keyword.
-** (6) tkTRIGGER The "trigger" keyword.
-** (7) tkEND The "end" keyword.
-**
-** Whitespace never causes a state transition and is always ignored.
-** This means that a SQL string of all whitespace is invalid.
-**
-** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
-** to recognize the end of a trigger can be omitted. All we have to do
-** is look for a semicolon that is not part of an string or comment.
-*/
+ /*
+ ** Return TRUE if the given SQL string ends in a semicolon.
+ **
+ ** Special handling is require for CREATE TRIGGER statements.
+ ** Whenever the CREATE TRIGGER keywords are seen, the statement
+ ** must end with ";END;".
+ **
+ ** This implementation uses a state machine with 8 states:
+ **
+ ** (0) INVALID We have not yet seen a non-whitespace character.
+ **
+ ** (1) START At the beginning or end of an SQL statement. This routine
+ ** returns 1 if it ends in the START state and 0 if it ends
+ ** in any other state.
+ **
+ ** (2) NORMAL We are in the middle of statement which ends with a single
+ ** semicolon.
+ **
+ ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
+ ** a statement.
+ **
+ ** (4) CREATE The keyword CREATE has been seen at the beginning of a
+ ** statement, possibly preceeded by EXPLAIN and/or followed by
+ ** TEMP or TEMPORARY
+ **
+ ** (5) TRIGGER We are in the middle of a trigger definition that must be
+ ** ended by a semicolon, the keyword END, and another semicolon.
+ **
+ ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
+ ** the end of a trigger definition.
+ **
+ ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
+ ** of a trigger difinition.
+ **
+ ** Transitions between states above are determined by tokens extracted
+ ** from the input. The following tokens are significant:
+ **
+ ** (0) tkSEMI A semicolon.
+ ** (1) tkWS Whitespace.
+ ** (2) tkOTHER Any other SQL token.
+ ** (3) tkEXPLAIN The "explain" keyword.
+ ** (4) tkCREATE The "create" keyword.
+ ** (5) tkTEMP The "temp" or "temporary" keyword.
+ ** (6) tkTRIGGER The "trigger" keyword.
+ ** (7) tkEND The "end" keyword.
+ **
+ ** Whitespace never causes a state transition and is always ignored.
+ ** This means that a SQL string of all whitespace is invalid.
+ **
+ ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
+ ** to recognize the end of a trigger can be omitted. All we have to do
+ ** is look for a semicolon that is not part of an string or comment.
+ */
- static public int sqlite3_complete( string zSql )
- {
- int state = 0; /* Current state, using numbers defined in header comment */
- int token; /* Value of the next token */
+ static public int sqlite3_complete(string zSql) {
+ int state = 0; /* Current state, using numbers defined in header comment */
+ int token; /* Value of the next token */
#if !SQLITE_OMIT_TRIGGER
- /* A complex statement machine used to detect the end of a CREATE TRIGGER
-** statement. This is the normal case.
-*/
- u8[][] trans = new u8[][] {
+ /* A complex statement machine used to detect the end of a CREATE TRIGGER
+ ** statement. This is the normal case.
+ */
+ u8[][] trans = new u8[][] {
/* Token: */
/* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
/* 0 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, },
@@ -156,179 +150,141 @@ static public int sqlite3_complete( string zSql )
};
#endif // * SQLITE_OMIT_TRIGGER */
- int zIdx = 0;
- while ( zIdx < zSql.Length )
- {
- switch ( zSql[zIdx] )
- {
- case ';':
- { /* A semicolon */
- token = tkSEMI;
- break;
- }
- case ' ':
- case '\r':
- case '\t':
- case '\n':
- case '\f':
- { /* White space is ignored */
- token = tkWS;
- break;
- }
- case '/':
- { /* C-style comments */
- if ( zSql[zIdx + 1] != '*' )
- {
- token = tkOTHER;
- break;
- }
- zIdx += 2;
- while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' )
- {
- zIdx++;
- }
- if ( zIdx == zSql.Length )
- return 0;
- zIdx++;
- token = tkWS;
- break;
- }
- case '-':
- { /* SQL-style comments from "--" to end of line */
- if ( zSql[zIdx + 1] != '-' )
- {
- token = tkOTHER;
- break;
- }
- while ( zIdx < zSql.Length && zSql[zIdx] != '\n' )
- {
- zIdx++;
- }
- if ( zIdx == zSql.Length )
- return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1;
- token = tkWS;
- break;
- }
- case '[':
- { /* Microsoft-style identifiers in [...] */
- zIdx++;
- while ( zIdx < zSql.Length && zSql[zIdx] != ']' )
- {
- zIdx++;
- }
- if ( zIdx == zSql.Length )
- return 0;
- token = tkOTHER;
- break;
- }
- case '`': /* Grave-accent quoted symbols used by MySQL */
- case '"': /* single- and double-quoted strings */
- case '\'':
- {
- int c = zSql[zIdx];
- zIdx++;
- while ( zIdx < zSql.Length && zSql[zIdx] != c )
- {
- zIdx++;
- }
- if ( zIdx == zSql.Length )
- return 0;
- token = tkOTHER;
- break;
- }
- default:
- {
-//#if SQLITE_EBCDIC
-// unsigned char c;
-//#endif
- if ( IdChar( (u8)zSql[zIdx] ) )
- {
- /* Keywords and unquoted identifiers */
- int nId;
- for ( nId = 1; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ); nId++ )
- {
- }
-#if SQLITE_OMIT_TRIGGER
+ int zIdx = 0;
+ while (zIdx < zSql.Length) {
+ switch (zSql[zIdx]) {
+ case ';': { /* A semicolon */
+ token = tkSEMI;
+ break;
+ }
+ case ' ':
+ case '\r':
+ case '\t':
+ case '\n':
+ case '\f': { /* White space is ignored */
+ token = tkWS;
+ break;
+ }
+ case '/': { /* C-style comments */
+ if (zSql[zIdx + 1] != '*') {
+ token = tkOTHER;
+ break;
+ }
+ zIdx += 2;
+ while (zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/') {
+ zIdx++;
+ }
+ if (zIdx == zSql.Length)
+ return 0;
+ zIdx++;
+ token = tkWS;
+ break;
+ }
+ case '-': { /* SQL-style comments from "--" to end of line */
+ if (zSql[zIdx + 1] != '-') {
+ token = tkOTHER;
+ break;
+ }
+ while (zIdx < zSql.Length && zSql[zIdx] != '\n') {
+ zIdx++;
+ }
+ if (zIdx == zSql.Length)
+ return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1;
+ token = tkWS;
+ break;
+ }
+ case '[': { /* Microsoft-style identifiers in [...] */
+ zIdx++;
+ while (zIdx < zSql.Length && zSql[zIdx] != ']') {
+ zIdx++;
+ }
+ if (zIdx == zSql.Length)
+ return 0;
+ token = tkOTHER;
+ break;
+ }
+ case '`': /* Grave-accent quoted symbols used by MySQL */
+ case '"': /* single- and double-quoted strings */
+ case '\'': {
+ int c = zSql[zIdx];
+ zIdx++;
+ while (zIdx < zSql.Length && zSql[zIdx] != c) {
+ zIdx++;
+ }
+ if (zIdx == zSql.Length)
+ return 0;
+ token = tkOTHER;
+ break;
+ }
+ default: {
+ //#if SQLITE_EBCDIC
+ // unsigned char c;
+ //#endif
+ if (IdChar((u8)zSql[zIdx])) {
+ /* Keywords and unquoted identifiers */
+ int nId;
+ for (nId = 1; (zIdx + nId) < zSql.Length && IdChar((u8)zSql[zIdx + nId]); nId++) {
+ }
+#if SQLITE_OMIT_TRIGGER
token = tkOTHER;
#else
- switch ( zSql[zIdx] )
- {
- case 'c':
- case 'C':
- {
- if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 )
- {
- token = tkCREATE;
- }
- else
- {
- token = tkOTHER;
- }
- break;
- }
- case 't':
- case 'T':
- {
- if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 )
- {
- token = tkTRIGGER;
- }
- else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 )
- {
- token = tkTEMP;
- }
- else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 )
- {
- token = tkTEMP;
- }
- else
- {
- token = tkOTHER;
- }
- break;
- }
- case 'e':
- case 'E':
- {
- if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 )
- {
- token = tkEND;
- }
- else
+ switch (zSql[zIdx]) {
+ case 'c':
+ case 'C': {
+ if (nId == 6 && sqlite3StrNICmp(zSql, zIdx, "create", 6) == 0) {
+ token = tkCREATE;
+ } else {
+ token = tkOTHER;
+ }
+ break;
+ }
+ case 't':
+ case 'T': {
+ if (nId == 7 && sqlite3StrNICmp(zSql, zIdx, "trigger", 7) == 0) {
+ token = tkTRIGGER;
+ } else if (nId == 4 && sqlite3StrNICmp(zSql, zIdx, "temp", 4) == 0) {
+ token = tkTEMP;
+ } else if (nId == 9 && sqlite3StrNICmp(zSql, zIdx, "temporary", 9) == 0) {
+ token = tkTEMP;
+ } else {
+ token = tkOTHER;
+ }
+ break;
+ }
+ case 'e':
+ case 'E': {
+ if (nId == 3 && sqlite3StrNICmp(zSql, zIdx, "end", 3) == 0) {
+ token = tkEND;
+ } else
#if !SQLITE_OMIT_EXPLAIN
- if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 )
- {
- token = tkEXPLAIN;
- }
- else
+ if (nId == 7 && sqlite3StrNICmp(zSql, zIdx, "explain", 7) == 0) {
+ token = tkEXPLAIN;
+ } else
#endif
- {
- token = tkOTHER;
+ {
+ token = tkOTHER;
+ }
+ break;
+ }
+ default: {
+ token = tkOTHER;
+ break;
+ }
+ }
+#endif // * SQLITE_OMIT_TRIGGER */
+ zIdx += nId - 1;
+ } else {
+ /* Operators and special symbols */
+ token = tkOTHER;
+ }
+ break;
}
- break;
- }
- default:
- {
- token = tkOTHER;
- break;
- }
}
-#endif // * SQLITE_OMIT_TRIGGER */
- zIdx += nId - 1;
- }
- else
- {
- /* Operators and special symbols */
- token = tkOTHER;
- }
- break;
+ state = trans[state][token];
+ zIdx++;
}
+ return (state == 1) ? 1 : 0;//return state==1;
}
- state = trans[state][token];
- zIdx++;
- }
- return ( state == 1 ) ? 1 : 0;//return state==1;
- }
#if !SQLITE_OMIT_UTF16
/*
@@ -358,5 +314,5 @@ int sqlite3_complete16(const void *zSql){
}
#endif // * SQLITE_OMIT_UTF16 */
#endif // * SQLITE_OMIT_COMPLETE */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/crypto.cs b/Src/IronPython.SQLite/c#sqlite/crypto.cs
index 5c3eec460..7c409ea59 100644
--- a/Src/IronPython.SQLite/c#sqlite/crypto.cs
+++ b/Src/IronPython.SQLite/c#sqlite/crypto.cs
@@ -1,63 +1,49 @@
-using System;
-using System.Diagnostics;
-using System.Text;
-
-using u8 = System.Byte;
-using u16 = System.UInt16;
-using Pgno = System.UInt32;
-
-namespace Community.CsharpSqlite
-{
- using sqlite3_int64 = System.Int64;
- using sqlite3_stmt = Sqlite3.Vdbe;
-#if !SQLITE_WINRT
- using System.Security.Cryptography;
- using System.IO;
+namespace Community.CsharpSqlite {
+#if !SQLITE_WINRT
#endif
- public partial class Sqlite3
- {
- /*
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2010 Noah B Hart, Diego Torres
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- *************************************************************************
- */
-
- /*
- ** SQLCipher
- ** crypto.c developed by Stephen Lombardo (Zetetic LLC)
- ** sjlombardo at zetetic dot net
- ** http://zetetic.net
- **
- ** Copyright (c) 2009, ZETETIC LLC
- ** All rights reserved.
- **
- ** Redistribution and use in source and binary forms, with or without
- ** modification, are permitted provided that the following conditions are met:
- ** * Redistributions of source code must retain the above copyright
- ** notice, this list of conditions and the following disclaimer.
- ** * Redistributions in binary form must reproduce the above copyright
- ** notice, this list of conditions and the following disclaimer in the
- ** documentation and/or other materials provided with the distribution.
- ** * Neither the name of the ZETETIC LLC nor the
- ** names of its contributors may be used to endorse or promote products
- ** derived from this software without specific prior written permission.
- **
- ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
- ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
- ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- **
- */
- /* BEGIN CRYPTO */
+ public partial class Sqlite3 {
+ /*
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2010 Noah B Hart, Diego Torres
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ *************************************************************************
+ */
+
+ /*
+ ** SQLCipher
+ ** crypto.c developed by Stephen Lombardo (Zetetic LLC)
+ ** sjlombardo at zetetic dot net
+ ** http://zetetic.net
+ **
+ ** Copyright (c) 2009, ZETETIC LLC
+ ** All rights reserved.
+ **
+ ** Redistribution and use in source and binary forms, with or without
+ ** modification, are permitted provided that the following conditions are met:
+ ** * Redistributions of source code must retain the above copyright
+ ** notice, this list of conditions and the following disclaimer.
+ ** * Redistributions in binary form must reproduce the above copyright
+ ** notice, this list of conditions and the following disclaimer in the
+ ** documentation and/or other materials provided with the distribution.
+ ** * Neither the name of the ZETETIC LLC nor the
+ ** names of its contributors may be used to endorse or promote products
+ ** derived from this software without specific prior written permission.
+ **
+ ** THIS SOFTWARE IS PROVIDED BY ZETETIC LLC ''AS IS'' AND ANY
+ ** EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ ** DISCLAIMED. IN NO EVENT SHALL ZETETIC LLC BE LIABLE FOR ANY
+ ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ **
+ */
+ /* BEGIN CRYPTO */
#if SQLITE_HAS_CODEC
//#include
@@ -758,8 +744,8 @@ static void sqlite3CodecGetKey( sqlite3 db, int nDb, out string zKey, out int nK
}
/* END CRYPTO */
#endif
- const int SQLITE_ENCRYPT_WRITE_CTX = 6; /* Encode page */
- const int SQLITE_ENCRYPT_READ_CTX = 7; /* Encode page */
- const int SQLITE_DECRYPT = 3; /* Decode page */
- }
+ const int SQLITE_ENCRYPT_WRITE_CTX = 6; /* Encode page */
+ const int SQLITE_ENCRYPT_READ_CTX = 7; /* Encode page */
+ const int SQLITE_DECRYPT = 3; /* Decode page */
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/ctime_c.cs b/Src/IronPython.SQLite/c#sqlite/ctime_c.cs
index 5f7917a0e..8e2a85a7b 100644
--- a/Src/IronPython.SQLite/c#sqlite/ctime_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/ctime_c.cs
@@ -1,48 +1,45 @@
#pragma warning disable CA1865 // Use char overload
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
- using System;
+namespace Community.CsharpSqlite {
+ using System;
- public partial class Sqlite3
- {
- /*
- ** 2010 February 23
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- **
- ** This file implements routines used to report what compile-time options
- ** SQLite was built with.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7
- **
- *************************************************************************
- */
+ public partial class Sqlite3 {
+ /*
+ ** 2010 February 23
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ **
+ ** This file implements routines used to report what compile-time options
+ ** SQLite was built with.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-01-28 17:03:50 ed759d5a9edb3bba5f48f243df47be29e3fe8cd7
+ **
+ *************************************************************************
+ */
#if !SQLITE_OMIT_COMPILEOPTION_DIAGS
- //#include "sqliteInt.h"
+ //#include "sqliteInt.h"
- /*
- ** An array of names of all compile-time options. This array should
- ** be sorted A-Z.
- **
- ** This array looks large, but in a typical installation actually uses
- ** only a handful of compile-time options, so most times this array is usually
- ** rather short and uses little memory space.
- */
- static string[] azCompileOpt = {
+ /*
+ ** An array of names of all compile-time options. This array should
+ ** be sorted A-Z.
+ **
+ ** This array looks large, but in a typical installation actually uses
+ ** only a handful of compile-time options, so most times this array is usually
+ ** rather short and uses little memory space.
+ */
+ static string[] azCompileOpt = {
/* These macros are provided to "stringify" the value of the define
** for those options in which the value is meaningful. */
@@ -376,47 +373,43 @@ public partial class Sqlite3
#endif
};
- /*
- ** Given the name of a compile-time option, return true if that option
- ** was used and false if not.
- **
- ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
- ** is not required for a match.
- */
- static int sqlite3_compileoption_used( string zOptName )
- {
- if ( zOptName.EndsWith( "=", StringComparison.Ordinal ) )
- return 0;
- int i, n = 0;
- if ( zOptName.StartsWith( "SQLITE_", System.StringComparison.OrdinalIgnoreCase ) )
- n = 7;
- //n = sqlite3Strlen30(zOptName);
+ /*
+ ** Given the name of a compile-time option, return true if that option
+ ** was used and false if not.
+ **
+ ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
+ ** is not required for a match.
+ */
+ static int sqlite3_compileoption_used(string zOptName) {
+ if (zOptName.EndsWith("=", StringComparison.Ordinal))
+ return 0;
+ int i, n = 0;
+ if (zOptName.StartsWith("SQLITE_", System.StringComparison.OrdinalIgnoreCase))
+ n = 7;
+ //n = sqlite3Strlen30(zOptName);
- /* Since ArraySize(azCompileOpt) is normally in single digits, a
- ** linear search is adequate. No need for a binary search. */
- if ( !String.IsNullOrEmpty( zOptName ) )
- for ( i = 0; i < ArraySize( azCompileOpt ); i++ )
- {
- int n1 = ( zOptName.Length-n < azCompileOpt[i].Length ) ? zOptName.Length-n : azCompileOpt[i].Length;
- if ( String.Compare( zOptName, n, azCompileOpt[i], 0, n1, StringComparison.OrdinalIgnoreCase ) == 0 )
- return 1;
+ /* Since ArraySize(azCompileOpt) is normally in single digits, a
+ ** linear search is adequate. No need for a binary search. */
+ if (!String.IsNullOrEmpty(zOptName))
+ for (i = 0; i < ArraySize(azCompileOpt); i++) {
+ int n1 = (zOptName.Length - n < azCompileOpt[i].Length) ? zOptName.Length - n : azCompileOpt[i].Length;
+ if (String.Compare(zOptName, n, azCompileOpt[i], 0, n1, StringComparison.OrdinalIgnoreCase) == 0)
+ return 1;
+ }
+ return 0;
}
- return 0;
- }
- /*
- ** Return the N-th compile-time option string. If N is out of range,
- ** return a NULL pointer.
- */
- static string sqlite3_compileoption_get( int N )
- {
- if ( N >= 0 && N < ArraySize( azCompileOpt ) )
- {
- return azCompileOpt[N];
- }
- return null;
- }
+ /*
+ ** Return the N-th compile-time option string. If N is out of range,
+ ** return a NULL pointer.
+ */
+ static string sqlite3_compileoption_get(int N) {
+ if (N >= 0 && N < ArraySize(azCompileOpt)) {
+ return azCompileOpt[N];
+ }
+ return null;
+ }
#endif //* SQLITE_OMIT_COMPILEOPTION_DIAGS */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/date_c.cs b/Src/IronPython.SQLite/c#sqlite/date_c.cs
index 4497a7722..9b30ea8a3 100644
--- a/Src/IronPython.SQLite/c#sqlite/date_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/date_c.cs
@@ -2,577 +2,515 @@
using System.Diagnostics;
using System.Text;
-using time_t = System.Int64;
-using sqlite3_int64 = System.Int64;
using i64 = System.Int64;
+using sqlite3_int64 = System.Int64;
+using time_t = System.Int64;
using u64 = System.UInt64;
-namespace Community.CsharpSqlite
-{
- using sqlite3_value = Sqlite3.Mem;
+namespace Community.CsharpSqlite {
+ using sqlite3_value = Sqlite3.Mem;
- public partial class Sqlite3
- {
- /*
- ** 2003 October 31
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This file contains the C functions that implement date and time
- ** functions for SQLite.
- **
- ** There is only one exported symbol in this file - the function
- ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
- ** All other code has file scope.
- **
- ** SQLite processes all times and dates as Julian Day numbers. The
- ** dates and times are stored as the number of days since noon
- ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
- ** calendar system.
- **
- ** 1970-01-01 00:00:00 is JD 2440587.5
- ** 2000-01-01 00:00:00 is JD 2451544.5
- **
- ** This implemention requires years to be expressed as a 4-digit number
- ** which means that only dates between 0000-01-01 and 9999-12-31 can
- ** be represented, even though julian day numbers allow a much wider
- ** range of dates.
- **
- ** The Gregorian calendar system is used for all dates and times,
- ** even those that predate the Gregorian calendar. Historians usually
- ** use the Julian calendar for dates prior to 1582-10-15 and for some
- ** dates afterwards, depending on locale. Beware of this difference.
- **
- ** The conversion algorithms are implemented based on descriptions
- ** in the following text:
- **
- ** Jean Meeus
- ** Astronomical Algorithms, 2nd Edition, 1998
- ** ISBM 0-943396-61-1
- ** Willmann-Bell, Inc
- ** Richmond, Virginia (USA)
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
- //#include
- //#include
- //#include
+ public partial class Sqlite3 {
+ /*
+ ** 2003 October 31
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains the C functions that implement date and time
+ ** functions for SQLite.
+ **
+ ** There is only one exported symbol in this file - the function
+ ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
+ ** All other code has file scope.
+ **
+ ** SQLite processes all times and dates as Julian Day numbers. The
+ ** dates and times are stored as the number of days since noon
+ ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
+ ** calendar system.
+ **
+ ** 1970-01-01 00:00:00 is JD 2440587.5
+ ** 2000-01-01 00:00:00 is JD 2451544.5
+ **
+ ** This implemention requires years to be expressed as a 4-digit number
+ ** which means that only dates between 0000-01-01 and 9999-12-31 can
+ ** be represented, even though julian day numbers allow a much wider
+ ** range of dates.
+ **
+ ** The Gregorian calendar system is used for all dates and times,
+ ** even those that predate the Gregorian calendar. Historians usually
+ ** use the Julian calendar for dates prior to 1582-10-15 and for some
+ ** dates afterwards, depending on locale. Beware of this difference.
+ **
+ ** The conversion algorithms are implemented based on descriptions
+ ** in the following text:
+ **
+ ** Jean Meeus
+ ** Astronomical Algorithms, 2nd Edition, 1998
+ ** ISBM 0-943396-61-1
+ ** Willmann-Bell, Inc
+ ** Richmond, Virginia (USA)
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
+ //#include
+ //#include
+ //#include
#if !SQLITE_OMIT_DATETIME_FUNCS
- /*
- ** A structure for holding a single date and time.
- */
- //typedef struct DateTime DateTime;
- public class DateTime
- {
- public sqlite3_int64 iJD; /* The julian day number times 86400000 */
- public int Y, M, D; /* Year, month, and day */
- public int h, m; /* Hour and minutes */
- public int tz; /* Timezone offset in minutes */
- public double s; /* Seconds */
- public byte validYMD; /* True (1) if Y,M,D are valid */
- public byte validHMS; /* True (1) if h,m,s are valid */
- public byte validJD; /* True (1) if iJD is valid */
- public byte validTZ; /* True (1) if tz is valid */
+ /*
+ ** A structure for holding a single date and time.
+ */
+ //typedef struct DateTime DateTime;
+ public class DateTime {
+ public sqlite3_int64 iJD; /* The julian day number times 86400000 */
+ public int Y, M, D; /* Year, month, and day */
+ public int h, m; /* Hour and minutes */
+ public int tz; /* Timezone offset in minutes */
+ public double s; /* Seconds */
+ public byte validYMD; /* True (1) if Y,M,D are valid */
+ public byte validHMS; /* True (1) if h,m,s are valid */
+ public byte validJD; /* True (1) if iJD is valid */
+ public byte validTZ; /* True (1) if tz is valid */
- public void CopyTo( DateTime ct )
- {
- ct.iJD = iJD;
- ct.Y = Y;
- ct.M = M;
- ct.D = D;
- ct.h = h;
- ct.m = m;
- ct.tz = tz;
- ct.s = s;
- ct.validYMD = validYMD;
- ct.validHMS = validHMS;
- ct.validJD = validJD;
- ct.validTZ = validJD;
- }
- };
+ public void CopyTo(DateTime ct) {
+ ct.iJD = iJD;
+ ct.Y = Y;
+ ct.M = M;
+ ct.D = D;
+ ct.h = h;
+ ct.m = m;
+ ct.tz = tz;
+ ct.s = s;
+ ct.validYMD = validYMD;
+ ct.validHMS = validHMS;
+ ct.validJD = validJD;
+ ct.validTZ = validJD;
+ }
+ };
- // Temporary String for use in this module
- static StringBuilder zdtTemp = new StringBuilder( 100 );
- static StringBuilder zdtBuf = new StringBuilder( 100 );
+ // Temporary String for use in this module
+ static StringBuilder zdtTemp = new StringBuilder(100);
+ static StringBuilder zdtBuf = new StringBuilder(100);
- /*
- ** Convert zDate into one or more integers. Additional arguments
- ** come in groups of 5 as follows:
- **
- ** N number of digits in the integer
- ** min minimum allowed value of the integer
- ** max maximum allowed value of the integer
- ** nextC first character after the integer
- ** pVal where to write the integers value.
- **
- ** Conversions continue until one with nextC==0 is encountered.
- ** The function returns the number of successful conversions.
- */
- static int getDigits( string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1 )
- {
- int c0 = getDigits( zDate + '\0', N0, min0, max0, nextC0, ref pVal0 );
- return c0 == 0 ? 0 : c0 + getDigits( zDate.Substring( zDate.IndexOf( nextC0 ) + 1 ) + '\0', N1, min1, max1, nextC1, ref pVal1 );
- }
- static int getDigits( string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1, int N2, int min2, int max2, char nextC2, ref int pVal2 )
- {
- int c0 = getDigits( zDate + '\0', N0, min0, max0, nextC0, ref pVal0 );
- if ( c0 == 0 )
- return 0;
- string zDate1 = zDate.Substring( zDate.IndexOf( nextC0 ) + 1 );
- int c1 = getDigits( zDate1 + '\0', N1, min1, max1, nextC1, ref pVal1 );
- if ( c1 == 0 )
- return c0;
- return c0 + c1 + getDigits( zDate1.Substring( zDate1.IndexOf( nextC1 ) + 1 ) + '\0', N2, min2, max2, nextC2, ref pVal2 );
- }
- static int getDigits( string zDate, int N, int min, int max, char nextC, ref int pVal )
- {
- //va_list ap;
- int val;
- //int N;
- //int min;
- //int max;
- //char nextC;
- //int pVal;
- int cnt = 0;
- //va_start( ap, zDate );
- int zIndex = 0;
- //do
- //{
- //N = va_arg( ap, ( Int32 ) 0 );
- //min = va_arg( ap, ( Int32 ) 0 );
- //max = va_arg( ap, ( Int32 ) 0 );
- //nextC = (char)va_arg( ap, "char" );
- //pVal = va_arg( ap, ( Int32 ) 0 );
- val = 0;
- while ( N-- != 0 )
- {
- if ( !sqlite3Isdigit( zDate[zIndex] ) )
- {
- goto end_getDigits;
+ /*
+ ** Convert zDate into one or more integers. Additional arguments
+ ** come in groups of 5 as follows:
+ **
+ ** N number of digits in the integer
+ ** min minimum allowed value of the integer
+ ** max maximum allowed value of the integer
+ ** nextC first character after the integer
+ ** pVal where to write the integers value.
+ **
+ ** Conversions continue until one with nextC==0 is encountered.
+ ** The function returns the number of successful conversions.
+ */
+ static int getDigits(string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1) {
+ int c0 = getDigits(zDate + '\0', N0, min0, max0, nextC0, ref pVal0);
+ return c0 == 0 ? 0 : c0 + getDigits(zDate.Substring(zDate.IndexOf(nextC0) + 1) + '\0', N1, min1, max1, nextC1, ref pVal1);
+ }
+ static int getDigits(string zDate, int N0, int min0, int max0, char nextC0, ref int pVal0, int N1, int min1, int max1, char nextC1, ref int pVal1, int N2, int min2, int max2, char nextC2, ref int pVal2) {
+ int c0 = getDigits(zDate + '\0', N0, min0, max0, nextC0, ref pVal0);
+ if (c0 == 0)
+ return 0;
+ string zDate1 = zDate.Substring(zDate.IndexOf(nextC0) + 1);
+ int c1 = getDigits(zDate1 + '\0', N1, min1, max1, nextC1, ref pVal1);
+ if (c1 == 0)
+ return c0;
+ return c0 + c1 + getDigits(zDate1.Substring(zDate1.IndexOf(nextC1) + 1) + '\0', N2, min2, max2, nextC2, ref pVal2);
+ }
+ static int getDigits(string zDate, int N, int min, int max, char nextC, ref int pVal) {
+ //va_list ap;
+ int val;
+ //int N;
+ //int min;
+ //int max;
+ //char nextC;
+ //int pVal;
+ int cnt = 0;
+ //va_start( ap, zDate );
+ int zIndex = 0;
+ //do
+ //{
+ //N = va_arg( ap, ( Int32 ) 0 );
+ //min = va_arg( ap, ( Int32 ) 0 );
+ //max = va_arg( ap, ( Int32 ) 0 );
+ //nextC = (char)va_arg( ap, "char" );
+ //pVal = va_arg( ap, ( Int32 ) 0 );
+ val = 0;
+ while (N-- != 0) {
+ if (!sqlite3Isdigit(zDate[zIndex])) {
+ goto end_getDigits;
+ }
+ val = val * 10 + zDate[zIndex] - '0';
+ zIndex++;
+ }
+ if (val < min || val > max || zIndex < zDate.Length && (nextC != 0 && nextC != zDate[zIndex])) {
+ goto end_getDigits;
+ }
+ pVal = val;
+ zIndex++;
+ cnt++;
+ //} while ( nextC != 0 && zIndex < zDate.Length );
+ end_getDigits:
+ //va_end( ap );
+ return cnt;
}
- val = val * 10 + zDate[zIndex] - '0';
- zIndex++;
- }
- if ( val < min || val > max || zIndex < zDate.Length && ( nextC != 0 && nextC != zDate[zIndex] ) )
- {
- goto end_getDigits;
- }
- pVal = val;
- zIndex++;
- cnt++;
-//} while ( nextC != 0 && zIndex < zDate.Length );
-end_getDigits:
- //va_end( ap );
- return cnt;
- }
-
- /*
- ** Parse a timezone extension on the end of a date-time.
- ** The extension is of the form:
- **
- ** (+/-)HH:MM
- **
- **
- ** Or the "zulu" notation:
- **
- ** Z
- **
- ** If the parse is successful, write the number of minutes
- ** of change in p.tz and return 0. If a parser error occurs,
- ** return non-zero.
- **
- ** A missing specifier is not considered an error.
- */
- static int parseTimezone( string zDate, DateTime p )
- {
- int sgn = 0;
- int nHr = 0;
- int nMn = 0;
- char c;
- zDate = zDate.Trim();// while ( sqlite3Isspace( *(u8)zDate ) ) { zDate++; }
- p.tz = 0;
- c = zDate.Length == 0 ? '\0' : zDate[0];
- if ( c == '-' )
- {
- sgn = -1;
- }
- else if ( c == '+' )
- {
- sgn = +1;
- }
- else if ( c == 'Z' || c == 'z' )
- {
- zDate = zDate.Substring( 1 ).Trim();//zDate++;
- goto zulu_time;
- }
- else
- {
- return c != '\0' ? 1 : 0;
- }
- //zDate++;
- if ( getDigits( zDate.Substring( 1 ), 2, 0, 14, ':', ref nHr, 2, 0, 59, '\0', ref nMn ) != 2 )
- {
- return 1;
- }
- //zDate += 5;
- p.tz = sgn * ( nMn + nHr * 60 );
- if ( zDate.Length == 6 )
- zDate = "";
- else if ( zDate.Length > 6 )
- zDate = zDate.Substring( 6 ).Trim();// while ( sqlite3Isspace( *(u8)zDate ) ) { zDate++; }
-zulu_time:
- return zDate != "" ? 1 : 0;
- }
- /*
- ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
- ** The HH, MM, and SS must each be exactly 2 digits. The
- ** fractional seconds FFFF can be one or more digits.
- **
- ** Return 1 if there is a parsing error and 0 on success.
- */
- static int parseHhMmSs( string zDate, DateTime p )
- {
- int h = 0;
- int m = 0;
- int s = 0;
- double ms = 0.0;
- if ( getDigits( zDate, 2, 0, 24, ':', ref h, 2, 0, 59, '\0', ref m ) != 2 )
- {
- return 1;
- }
- int zIndex = 5;// zDate += 5;
- if ( zIndex < zDate.Length && zDate[zIndex] == ':' )
- {
- zIndex++;// zDate++;
- if ( getDigits( zDate.Substring( zIndex ), 2, 0, 59, '\0', ref s ) != 1 )
- {
- return 1;
+ /*
+ ** Parse a timezone extension on the end of a date-time.
+ ** The extension is of the form:
+ **
+ ** (+/-)HH:MM
+ **
+ **
+ ** Or the "zulu" notation:
+ **
+ ** Z
+ **
+ ** If the parse is successful, write the number of minutes
+ ** of change in p.tz and return 0. If a parser error occurs,
+ ** return non-zero.
+ **
+ ** A missing specifier is not considered an error.
+ */
+ static int parseTimezone(string zDate, DateTime p) {
+ int sgn = 0;
+ int nHr = 0;
+ int nMn = 0;
+ char c;
+ zDate = zDate.Trim();// while ( sqlite3Isspace( *(u8)zDate ) ) { zDate++; }
+ p.tz = 0;
+ c = zDate.Length == 0 ? '\0' : zDate[0];
+ if (c == '-') {
+ sgn = -1;
+ } else if (c == '+') {
+ sgn = +1;
+ } else if (c == 'Z' || c == 'z') {
+ zDate = zDate.Substring(1).Trim();//zDate++;
+ goto zulu_time;
+ } else {
+ return c != '\0' ? 1 : 0;
+ }
+ //zDate++;
+ if (getDigits(zDate.Substring(1), 2, 0, 14, ':', ref nHr, 2, 0, 59, '\0', ref nMn) != 2) {
+ return 1;
+ }
+ //zDate += 5;
+ p.tz = sgn * (nMn + nHr * 60);
+ if (zDate.Length == 6)
+ zDate = "";
+ else if (zDate.Length > 6)
+ zDate = zDate.Substring(6).Trim();// while ( sqlite3Isspace( *(u8)zDate ) ) { zDate++; }
+ zulu_time:
+ return zDate != "" ? 1 : 0;
}
- zIndex += 2;// zDate += 2;
- if ( zIndex + 1 < zDate.Length && zDate[zIndex] == '.' && sqlite3Isdigit( zDate[zIndex + 1] ) )
- {
- double rScale = 1.0;
- zIndex++;// zDate++;
- while ( zIndex < zDate.Length && sqlite3Isdigit( zDate[zIndex] )
- )
- {
- ms = ms * 10.0 + zDate[zIndex] - '0';
- rScale *= 10.0;
- zIndex++;//zDate++;
- }
- ms /= rScale;
+
+ /*
+ ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
+ ** The HH, MM, and SS must each be exactly 2 digits. The
+ ** fractional seconds FFFF can be one or more digits.
+ **
+ ** Return 1 if there is a parsing error and 0 on success.
+ */
+ static int parseHhMmSs(string zDate, DateTime p) {
+ int h = 0;
+ int m = 0;
+ int s = 0;
+ double ms = 0.0;
+ if (getDigits(zDate, 2, 0, 24, ':', ref h, 2, 0, 59, '\0', ref m) != 2) {
+ return 1;
+ }
+ int zIndex = 5;// zDate += 5;
+ if (zIndex < zDate.Length && zDate[zIndex] == ':') {
+ zIndex++;// zDate++;
+ if (getDigits(zDate.Substring(zIndex), 2, 0, 59, '\0', ref s) != 1) {
+ return 1;
+ }
+ zIndex += 2;// zDate += 2;
+ if (zIndex + 1 < zDate.Length && zDate[zIndex] == '.' && sqlite3Isdigit(zDate[zIndex + 1])) {
+ double rScale = 1.0;
+ zIndex++;// zDate++;
+ while (zIndex < zDate.Length && sqlite3Isdigit(zDate[zIndex])
+ ) {
+ ms = ms * 10.0 + zDate[zIndex] - '0';
+ rScale *= 10.0;
+ zIndex++;//zDate++;
+ }
+ ms /= rScale;
+ }
+ } else {
+ s = 0;
+ }
+ p.validJD = 0;
+ p.validHMS = 1;
+ p.h = h;
+ p.m = m;
+ p.s = s + ms;
+ if (zIndex < zDate.Length && parseTimezone(zDate.Substring(zIndex), p) != 0)
+ return 1;
+ p.validTZ = (byte)((p.tz != 0) ? 1 : 0);
+ return 0;
}
- }
- else
- {
- s = 0;
- }
- p.validJD = 0;
- p.validHMS = 1;
- p.h = h;
- p.m = m;
- p.s = s + ms;
- if ( zIndex < zDate.Length && parseTimezone( zDate.Substring( zIndex ), p ) != 0 )
- return 1;
- p.validTZ = (byte)( ( p.tz != 0 ) ? 1 : 0 );
- return 0;
- }
- /*
- ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
- ** that the YYYY-MM-DD is according to the Gregorian calendar.
- **
- ** Reference: Meeus page 61
- */
- static void computeJD( DateTime p )
- {
- int Y, M, D, A, B, X1, X2;
+ /*
+ ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
+ ** that the YYYY-MM-DD is according to the Gregorian calendar.
+ **
+ ** Reference: Meeus page 61
+ */
+ static void computeJD(DateTime p) {
+ int Y, M, D, A, B, X1, X2;
- if ( p.validJD != 0 )
- return;
- if ( p.validYMD != 0 )
- {
- Y = p.Y;
- M = p.M;
- D = p.D;
- }
- else
- {
- Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
- M = 1;
- D = 1;
- }
- if ( M <= 2 )
- {
- Y--;
- M += 12;
- }
- A = Y / 100;
- B = 2 - A + ( A / 4 );
- X1 = (int)( 36525 * ( Y + 4716 ) / 100 );
- X2 = (int)( 306001 * ( M + 1 ) / 10000 );
- p.iJD = (long)( ( X1 + X2 + D + B - 1524.5 ) * 86400000 );
- p.validJD = 1;
- if ( p.validHMS != 0 )
- {
- p.iJD += (long)( p.h * 3600000 + p.m * 60000 + p.s * 1000 );
- if ( p.validTZ != 0 )
- {
- p.iJD -= p.tz * 60000;
- p.validYMD = 0;
- p.validHMS = 0;
- p.validTZ = 0;
+ if (p.validJD != 0)
+ return;
+ if (p.validYMD != 0) {
+ Y = p.Y;
+ M = p.M;
+ D = p.D;
+ } else {
+ Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
+ M = 1;
+ D = 1;
+ }
+ if (M <= 2) {
+ Y--;
+ M += 12;
+ }
+ A = Y / 100;
+ B = 2 - A + (A / 4);
+ X1 = (int)(36525 * (Y + 4716) / 100);
+ X2 = (int)(306001 * (M + 1) / 10000);
+ p.iJD = (long)((X1 + X2 + D + B - 1524.5) * 86400000);
+ p.validJD = 1;
+ if (p.validHMS != 0) {
+ p.iJD += (long)(p.h * 3600000 + p.m * 60000 + p.s * 1000);
+ if (p.validTZ != 0) {
+ p.iJD -= p.tz * 60000;
+ p.validYMD = 0;
+ p.validHMS = 0;
+ p.validTZ = 0;
+ }
+ }
}
- }
- }
- /*
- ** Parse dates of the form
- **
- ** YYYY-MM-DD HH:MM:SS.FFF
- ** YYYY-MM-DD HH:MM:SS
- ** YYYY-MM-DD HH:MM
- ** YYYY-MM-DD
- **
- ** Write the result into the DateTime structure and return 0
- ** on success and 1 if the input string is not a well-formed
- ** date.
- */
- static int parseYyyyMmDd( string zDate, DateTime p )
- {
- int Y = 0;
- int M = 0;
- int D = 0;
- bool neg;
+ /*
+ ** Parse dates of the form
+ **
+ ** YYYY-MM-DD HH:MM:SS.FFF
+ ** YYYY-MM-DD HH:MM:SS
+ ** YYYY-MM-DD HH:MM
+ ** YYYY-MM-DD
+ **
+ ** Write the result into the DateTime structure and return 0
+ ** on success and 1 if the input string is not a well-formed
+ ** date.
+ */
+ static int parseYyyyMmDd(string zDate, DateTime p) {
+ int Y = 0;
+ int M = 0;
+ int D = 0;
+ bool neg;
- int zIndex = 0;
- if ( zDate[zIndex] == '-' )
- {
- zIndex++;// zDate++;
- neg = true;
- }
- else
- {
- neg = false;
- }
- if ( getDigits( zDate.Substring( zIndex ), 4, 0, 9999, '-', ref Y, 2, 1, 12, '-', ref M, 2, 1, 31, '\0', ref D ) != 3 )
- {
- return 1;
- }
- zIndex += 10;// zDate += 10;
- while ( zIndex < zDate.Length && ( sqlite3Isspace( zDate[zIndex] ) || 'T' == zDate[zIndex] ) )
- {
- zIndex++;
- }//zDate++; }
- if ( zIndex < zDate.Length && parseHhMmSs( zDate.Substring( zIndex ), p ) == 0 )
- {
- /* We got the time */
- }
- else if ( zIndex >= zDate.Length )// zDate[zIndex] == '\0')
- {
- p.validHMS = 0;
- }
- else
- {
- return 1;
- }
- p.validJD = 0;
- p.validYMD = 1;
- p.Y = neg ? -Y : Y;
- p.M = M;
- p.D = D;
- if ( p.validTZ != 0 )
- {
- computeJD( p );
- }
- return 0;
- }
+ int zIndex = 0;
+ if (zDate[zIndex] == '-') {
+ zIndex++;// zDate++;
+ neg = true;
+ } else {
+ neg = false;
+ }
+ if (getDigits(zDate.Substring(zIndex), 4, 0, 9999, '-', ref Y, 2, 1, 12, '-', ref M, 2, 1, 31, '\0', ref D) != 3) {
+ return 1;
+ }
+ zIndex += 10;// zDate += 10;
+ while (zIndex < zDate.Length && (sqlite3Isspace(zDate[zIndex]) || 'T' == zDate[zIndex])) {
+ zIndex++;
+ }//zDate++; }
+ if (zIndex < zDate.Length && parseHhMmSs(zDate.Substring(zIndex), p) == 0) {
+ /* We got the time */
+ } else if (zIndex >= zDate.Length)// zDate[zIndex] == '\0')
+ {
+ p.validHMS = 0;
+ } else {
+ return 1;
+ }
+ p.validJD = 0;
+ p.validYMD = 1;
+ p.Y = neg ? -Y : Y;
+ p.M = M;
+ p.D = D;
+ if (p.validTZ != 0) {
+ computeJD(p);
+ }
+ return 0;
+ }
- /*
- ** Set the time to the current time reported by the VFS
- */
- static void setDateTimeToCurrent( sqlite3_context context, DateTime p )
- {
- sqlite3 db = sqlite3_context_db_handle( context );
- sqlite3OsCurrentTimeInt64( db.pVfs, ref p.iJD );
- p.validJD = 1;
- }
+ /*
+ ** Set the time to the current time reported by the VFS
+ */
+ static void setDateTimeToCurrent(sqlite3_context context, DateTime p) {
+ sqlite3 db = sqlite3_context_db_handle(context);
+ sqlite3OsCurrentTimeInt64(db.pVfs, ref p.iJD);
+ p.validJD = 1;
+ }
- /*
- ** Attempt to parse the given string into a Julian Day Number. Return
- ** the number of errors.
- **
- ** The following are acceptable forms for the input string:
- **
- ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
- ** DDDD.DD
- ** now
- **
- ** In the first form, the +/-HH:MM is always optional. The fractional
- ** seconds extension (the ".FFF") is optional. The seconds portion
- ** (":SS.FFF") is option. The year and date can be omitted as long
- ** as there is a time string. The time string can be omitted as long
- ** as there is a year and date.
- */
- static int parseDateOrTime(
- sqlite3_context context,
- string zDate,
- ref DateTime p
- )
- {
- double r = 0.0;
- if ( parseYyyyMmDd( zDate, p ) == 0 )
- {
- return 0;
- }
- else if ( parseHhMmSs( zDate, p ) == 0 )
- {
- return 0;
- }
- else if ( zDate.Equals( "now", StringComparison.OrdinalIgnoreCase ) )
- {
- setDateTimeToCurrent( context, p );
- return 0;
- }
- else if ( sqlite3AtoF( zDate, ref r, sqlite3Strlen30( zDate ), SQLITE_UTF8 ) )
- {
- p.iJD = (sqlite3_int64)( r * 86400000.0 + 0.5 );
- p.validJD = 1;
- return 0;
- }
- return 1;
- }
+ /*
+ ** Attempt to parse the given string into a Julian Day Number. Return
+ ** the number of errors.
+ **
+ ** The following are acceptable forms for the input string:
+ **
+ ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
+ ** DDDD.DD
+ ** now
+ **
+ ** In the first form, the +/-HH:MM is always optional. The fractional
+ ** seconds extension (the ".FFF") is optional. The seconds portion
+ ** (":SS.FFF") is option. The year and date can be omitted as long
+ ** as there is a time string. The time string can be omitted as long
+ ** as there is a year and date.
+ */
+ static int parseDateOrTime(
+ sqlite3_context context,
+ string zDate,
+ ref DateTime p
+ ) {
+ double r = 0.0;
+ if (parseYyyyMmDd(zDate, p) == 0) {
+ return 0;
+ } else if (parseHhMmSs(zDate, p) == 0) {
+ return 0;
+ } else if (zDate.Equals("now", StringComparison.OrdinalIgnoreCase)) {
+ setDateTimeToCurrent(context, p);
+ return 0;
+ } else if (sqlite3AtoF(zDate, ref r, sqlite3Strlen30(zDate), SQLITE_UTF8)) {
+ p.iJD = (sqlite3_int64)(r * 86400000.0 + 0.5);
+ p.validJD = 1;
+ return 0;
+ }
+ return 1;
+ }
- /*
- ** Compute the Year, Month, and Day from the julian day number.
- */
- static void computeYMD( DateTime p )
- {
- int Z, A, B, C, D, E, X1;
- if ( p.validYMD != 0 )
- return;
- if ( 0 == p.validJD )
- {
- p.Y = 2000;
- p.M = 1;
- p.D = 1;
- }
- else
- {
- Z = (int)( ( p.iJD + 43200000 ) / 86400000 );
- A = (int)( ( Z - 1867216.25 ) / 36524.25 );
- A = Z + 1 + A - ( A / 4 );
- B = A + 1524;
- C = (int)( ( B - 122.1 ) / 365.25 );
- D = (int)( ( 36525 * C ) / 100 );
- E = (int)( ( B - D ) / 30.6001 );
- X1 = (int)( 30.6001 * E );
- p.D = B - D - X1;
- p.M = E < 14 ? E - 1 : E - 13;
- p.Y = p.M > 2 ? C - 4716 : C - 4715;
- }
- p.validYMD = 1;
- }
+ /*
+ ** Compute the Year, Month, and Day from the julian day number.
+ */
+ static void computeYMD(DateTime p) {
+ int Z, A, B, C, D, E, X1;
+ if (p.validYMD != 0)
+ return;
+ if (0 == p.validJD) {
+ p.Y = 2000;
+ p.M = 1;
+ p.D = 1;
+ } else {
+ Z = (int)((p.iJD + 43200000) / 86400000);
+ A = (int)((Z - 1867216.25) / 36524.25);
+ A = Z + 1 + A - (A / 4);
+ B = A + 1524;
+ C = (int)((B - 122.1) / 365.25);
+ D = (int)((36525 * C) / 100);
+ E = (int)((B - D) / 30.6001);
+ X1 = (int)(30.6001 * E);
+ p.D = B - D - X1;
+ p.M = E < 14 ? E - 1 : E - 13;
+ p.Y = p.M > 2 ? C - 4716 : C - 4715;
+ }
+ p.validYMD = 1;
+ }
- /*
- ** Compute the Hour, Minute, and Seconds from the julian day number.
- */
- static void computeHMS( DateTime p )
- {
- int s;
- if ( p.validHMS != 0 )
- return;
- computeJD( p );
- s = (int)( ( p.iJD + 43200000 ) % 86400000 );
- p.s = s / 1000.0;
- s = (int)p.s;
- p.s -= s;
- p.h = s / 3600;
- s -= p.h * 3600;
- p.m = s / 60;
- p.s += s - p.m * 60;
- p.validHMS = 1;
- }
+ /*
+ ** Compute the Hour, Minute, and Seconds from the julian day number.
+ */
+ static void computeHMS(DateTime p) {
+ int s;
+ if (p.validHMS != 0)
+ return;
+ computeJD(p);
+ s = (int)((p.iJD + 43200000) % 86400000);
+ p.s = s / 1000.0;
+ s = (int)p.s;
+ p.s -= s;
+ p.h = s / 3600;
+ s -= p.h * 3600;
+ p.m = s / 60;
+ p.s += s - p.m * 60;
+ p.validHMS = 1;
+ }
- /*
- ** Compute both YMD and HMS
- */
- static void computeYMD_HMS( DateTime p )
- {
- computeYMD( p );
- computeHMS( p );
- }
+ /*
+ ** Compute both YMD and HMS
+ */
+ static void computeYMD_HMS(DateTime p) {
+ computeYMD(p);
+ computeHMS(p);
+ }
- /*
- ** Clear the YMD and HMS and the TZ
- */
- static void clearYMD_HMS_TZ( DateTime p )
- {
- p.validYMD = 0;
- p.validHMS = 0;
- p.validTZ = 0;
- }
+ /*
+ ** Clear the YMD and HMS and the TZ
+ */
+ static void clearYMD_HMS_TZ(DateTime p) {
+ p.validYMD = 0;
+ p.validHMS = 0;
+ p.validTZ = 0;
+ }
- /*
- ** On recent Windows platforms, the localtime_s() function is available
- ** as part of the "Secure CRT". It is essentially equivalent to
- ** localtime_r() available under most POSIX platforms, except that the
- ** order of the parameters is reversed.
- **
- ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
- **
- ** If the user has not indicated to use localtime_r() or localtime_s()
- ** already, check for an MSVC build environment that provides
- ** localtime_s().
- */
- //#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
- // defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
- //#define HAVE_LOCALTIME_S 1
- //#endif
+ /*
+ ** On recent Windows platforms, the localtime_s() function is available
+ ** as part of the "Secure CRT". It is essentially equivalent to
+ ** localtime_r() available under most POSIX platforms, except that the
+ ** order of the parameters is reversed.
+ **
+ ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
+ **
+ ** If the user has not indicated to use localtime_r() or localtime_s()
+ ** already, check for an MSVC build environment that provides
+ ** localtime_s().
+ */
+ //#if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
+ // defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
+ //#define HAVE_LOCALTIME_S 1
+ //#endif
#if !SQLITE_OMIT_LOCALTIME
- /*
- ** The following routine implements the rough equivalent of localtime_r()
- ** using whatever operating-system specific localtime facility that
- ** is available. This routine returns 0 on success and
- ** non-zero on any kind of error.
- **
- ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
- ** routine will always fail.
- */
- static int osLocaltime( time_t t, ref tm pTm )
- {
- int rc;
+ /*
+ ** The following routine implements the rough equivalent of localtime_r()
+ ** using whatever operating-system specific localtime facility that
+ ** is available. This routine returns 0 on success and
+ ** non-zero on any kind of error.
+ **
+ ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
+ ** routine will always fail.
+ */
+ static int osLocaltime(time_t t, ref tm pTm) {
+ int rc;
#if (!(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) && (!(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
- tm pX;
- sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER );
- sqlite3_mutex_enter( mutex );
- pX = localtime( t );
+ tm pX;
+ sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
+ sqlite3_mutex_enter(mutex);
+ pX = localtime(t);
#if !SQLITE_OMIT_BUILTIN_TEST
- if ( sqlite3GlobalConfig.bLocaltimeFault )
- pX = null;
+ if (sqlite3GlobalConfig.bLocaltimeFault)
+ pX = null;
#endif
- if ( pX != null )
- pTm = pX;
- sqlite3_mutex_leave( mutex );
- rc = pX == null ? 1 : 0;
+ if (pX != null)
+ pTm = pX;
+ sqlite3_mutex_leave(mutex);
+ rc = pX == null ? 1 : 0;
#else
#if !SQLITE_OMIT_BUILTIN_TEST
if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
@@ -583,746 +521,662 @@ static int osLocaltime( time_t t, ref tm pTm )
rc = localtime_s(pTm, t);
#endif //* HAVE_LOCALTIME_R */
#endif //* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
- return rc;
- }
+ return rc;
+ }
#endif //* SQLITE_OMIT_LOCALTIME */
#if !SQLITE_OMIT_LOCALTIME
- /*
-** Compute the difference (in milliseconds) between localtime and UTC
-** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
-** return this value and set *pRc to SQLITE_OK.
-**
-** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
-** is undefined in this case.
-*/
- static sqlite3_int64 localtimeOffset(
- DateTime p, /* Date at which to calculate offset */
- sqlite3_context pCtx, /* Write error here if one occurs */
- out int pRc /* OUT: Error code. SQLITE_OK or ERROR */
- )
- {
- DateTime x;
- DateTime y = new DateTime();
- time_t t;
- tm sLocal = new tm();
+ /*
+ ** Compute the difference (in milliseconds) between localtime and UTC
+ ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
+ ** return this value and set *pRc to SQLITE_OK.
+ **
+ ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
+ ** is undefined in this case.
+ */
+ static sqlite3_int64 localtimeOffset(
+ DateTime p, /* Date at which to calculate offset */
+ sqlite3_context pCtx, /* Write error here if one occurs */
+ out int pRc /* OUT: Error code. SQLITE_OK or ERROR */
+ ) {
+ DateTime x;
+ DateTime y = new DateTime();
+ time_t t;
+ tm sLocal = new tm();
- /* Initialize the contents of sLocal to avoid a compiler warning. */
- //memset(&sLocal, 0, sizeof(sLocal));
+ /* Initialize the contents of sLocal to avoid a compiler warning. */
+ //memset(&sLocal, 0, sizeof(sLocal));
- x = p;
- computeYMD_HMS( x );
- if ( x.Y < 1971 || x.Y >= 2038 )
- {
- x.Y = 2000;
- x.M = 1;
- x.D = 1;
- x.h = 0;
- x.m = 0;
- x.s = 0.0;
- }
- else
- {
- int s = (int)( x.s + 0.5 );
- x.s = s;
- }
- x.tz = 0;
- x.validJD = 0;
- computeJD( x );
- t = (long)( x.iJD / 1000 - 210866760000L );// (time_t)(x.iJD/1000 - 21086676*(i64)10000);
- if ( osLocaltime( t, ref sLocal ) != 0 )
- {
- sqlite3_result_error( pCtx, "local time unavailable", -1 );
- pRc = SQLITE_ERROR;
- return 0;
- }
- y.Y = sLocal.tm_year;// +1900;
- y.M = sLocal.tm_mon;// +1;
- y.D = sLocal.tm_mday;
- y.h = sLocal.tm_hour;
- y.m = sLocal.tm_min;
- y.s = sLocal.tm_sec;
- y.validYMD = 1;
- y.validHMS = 1;
- y.validJD = 0;
- y.validTZ = 0;
- computeJD( y );
- pRc = SQLITE_OK;
- return (int)( y.iJD - x.iJD );
- }
+ x = p;
+ computeYMD_HMS(x);
+ if (x.Y < 1971 || x.Y >= 2038) {
+ x.Y = 2000;
+ x.M = 1;
+ x.D = 1;
+ x.h = 0;
+ x.m = 0;
+ x.s = 0.0;
+ } else {
+ int s = (int)(x.s + 0.5);
+ x.s = s;
+ }
+ x.tz = 0;
+ x.validJD = 0;
+ computeJD(x);
+ t = (long)(x.iJD / 1000 - 210866760000L);// (time_t)(x.iJD/1000 - 21086676*(i64)10000);
+ if (osLocaltime(t, ref sLocal) != 0) {
+ sqlite3_result_error(pCtx, "local time unavailable", -1);
+ pRc = SQLITE_ERROR;
+ return 0;
+ }
+ y.Y = sLocal.tm_year;// +1900;
+ y.M = sLocal.tm_mon;// +1;
+ y.D = sLocal.tm_mday;
+ y.h = sLocal.tm_hour;
+ y.m = sLocal.tm_min;
+ y.s = sLocal.tm_sec;
+ y.validYMD = 1;
+ y.validHMS = 1;
+ y.validJD = 0;
+ y.validTZ = 0;
+ computeJD(y);
+ pRc = SQLITE_OK;
+ return (int)(y.iJD - x.iJD);
+ }
#endif //* SQLITE_OMIT_LOCALTIME */
- /*
-** Process a modifier to a date-time stamp. The modifiers are
-** as follows:
-**
-** NNN days
-** NNN hours
-** NNN minutes
-** NNN.NNNN seconds
-** NNN months
-** NNN years
-** start of month
-** start of year
-** start of week
-** start of day
-** weekday N
-** unixepoch
-** localtime
-** utc
-**
-** Return 0 on success and 1 if there is any kind of error. If the error
-** is in a system call (i.e. localtime()), then an error message is written
-** to context pCtx. If the error is an unrecognized modifier, no error is
-** written to pCtx.
-*/
- static int parseModifier( sqlite3_context pCtx, string zMod, DateTime p )
- {
- int rc = 1;
- int n;
- double r = 0;
- StringBuilder z = new StringBuilder( zMod.ToLowerInvariant() );
- zdtBuf.Length = 0;
- //z = zdtBuf;
- //for(n=0; niJD = p->iJD/86400 + 21086676*(i64)10000000;
- clearYMD_HMS_TZ( p );
- rc = 0;
- }
-#if !SQLITE_OMIT_LOCALTIME
- else if ( z.ToString() == "utc" )
- {
- long c1;
- computeJD( p );
- c1 = localtimeOffset( p, pCtx, out rc );
- if ( rc == SQLITE_OK )
- {
- p.iJD -= c1;
- clearYMD_HMS_TZ( p );
- p.iJD += c1 - localtimeOffset( p, pCtx, out rc );
- }
- }
+ case 'u': {
+ /*
+ ** unixepoch
+ **
+ ** Treat the current value of p.iJD as the number of
+ ** seconds since 1970. Convert to a real julian day number.
+ */
+ if (z.ToString() == "unixepoch" && p.validJD != 0) {
+ p.iJD = (long)((p.iJD + 43200) / 86400 + 210866760000000L);//p->iJD = p->iJD/86400 + 21086676*(i64)10000000;
+ clearYMD_HMS_TZ(p);
+ rc = 0;
+ }
+#if !SQLITE_OMIT_LOCALTIME
+ else if (z.ToString() == "utc") {
+ long c1;
+ computeJD(p);
+ c1 = localtimeOffset(p, pCtx, out rc);
+ if (rc == SQLITE_OK) {
+ p.iJD -= c1;
+ clearYMD_HMS_TZ(p);
+ p.iJD += c1 - localtimeOffset(p, pCtx, out rc);
+ }
+ }
#endif
- break;
- }
- case 'w':
- {
- /*
- ** weekday N
- **
- ** Move the date to the same time on the next occurrence of
- ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
- ** date is already on the appropriate weekday, this is a no-op.
- */
- if ( z.ToString().StartsWith( "weekday ", StringComparison.Ordinal )
- && sqlite3AtoF( z.ToString().Substring( 8 ), ref r, sqlite3Strlen30( z.ToString().Substring( 8 ) ), SQLITE_UTF8 )
- && ( n = (int)r ) == r && n >= 0 && r < 7 )
- {
- sqlite3_int64 Z;
- computeYMD_HMS( p );
- p.validTZ = 0;
- p.validJD = 0;
- computeJD( p );
- Z = ( ( p.iJD + 129600000 ) / 86400000 ) % 7;
- if ( Z > n )
- Z -= 7;
- p.iJD += ( n - Z ) * 86400000;
- clearYMD_HMS_TZ( p );
- rc = 0;
- }
- break;
- }
- case 's':
- {
- /*
- ** start of TTTTT
- **
- ** Move the date backwards to the beginning of the current day,
- ** or month or year.
- */
- if ( z.Length <= 9 )
- z.Length = 0;
- else
- z.Remove( 0, 9 );//z += 9;
- computeYMD( p );
- p.validHMS = 1;
- p.h = p.m = 0;
- p.s = 0.0;
- p.validTZ = 0;
- p.validJD = 0;
- if ( z.ToString() == "month" )
- {
- p.D = 1;
- rc = 0;
- }
- else if ( z.ToString() == "year" )
- {
- computeYMD( p );
- p.M = 1;
- p.D = 1;
- rc = 0;
- }
- else if ( z.ToString() == "day" )
- {
- rc = 0;
- }
- break;
- }
- case '+':
- case '-':
- case '0':
- case '1':
- case '2':
- case '3':
- case '4':
- case '5':
- case '6':
- case '7':
- case '8':
- case '9':
- {
- double rRounder;
- for ( n = 1; n < z.Length && z[n] != ':' && !sqlite3Isspace( z[n] ); n++ )
- {
- }
- if ( !sqlite3AtoF( z.ToString(), ref r, n, SQLITE_UTF8 ) )
- {
- rc = 1;
- break;
- }
- Debug.Assert( n >= 1 );
- if ( z[n] == ':' )
- {
- /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
- ** specified number of hours, minutes, seconds, and fractional seconds
- ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
- ** omitted.
- */
- string z2 = z.ToString();
- DateTime tx;
- sqlite3_int64 day;
- int z2Index = 0;
- if ( !sqlite3Isdigit( z2[z2Index] ) )
- z2Index++;// z2++;
- tx = new DateTime();// memset( &tx, 0, sizeof(tx));
- if ( parseHhMmSs( z2.Substring( z2Index ), tx ) != 0 )
- break;
- computeJD( tx );
- tx.iJD -= 43200000;
- day = tx.iJD / 86400000;
- tx.iJD -= day * 86400000;
- if ( z[0] == '-' )
- tx.iJD = -tx.iJD;
- computeJD( p );
- clearYMD_HMS_TZ( p );
- p.iJD += tx.iJD;
- rc = 0;
- break;
- }
- //z += n;
- while ( sqlite3Isspace( z[n] ) )
- n++;// z++;
- z = z.Remove( 0, n );
- n = sqlite3Strlen30( z );
- if ( n > 10 || n < 3 )
- break;
- if ( z[n - 1] == 's' )
- {
- z.Length = --n;
- }// z[n - 1] = '\0'; n--; }
- computeJD( p );
- rc = 0;
- rRounder = r < 0 ? -0.5 : +0.5;
- if ( n == 3 && z.ToString() == "day" )
- {
- p.iJD += (long)( r * 86400000.0 + rRounder );
- }
- else if ( n == 4 && z.ToString() == "hour" )
- {
- p.iJD += (long)( r * ( 86400000.0 / 24.0 ) + rRounder );
- }
- else if ( n == 6 && z.ToString() == "minute" )
- {
- p.iJD += (long)( r * ( 86400000.0 / ( 24.0 * 60.0 ) ) + rRounder );
- }
- else if ( n == 6 && z.ToString() == "second" )
- {
- p.iJD += (long)( r * ( 86400000.0 / ( 24.0 * 60.0 * 60.0 ) ) + rRounder );
+ break;
+ }
+ case 'w': {
+ /*
+ ** weekday N
+ **
+ ** Move the date to the same time on the next occurrence of
+ ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
+ ** date is already on the appropriate weekday, this is a no-op.
+ */
+ if (z.ToString().StartsWith("weekday ", StringComparison.Ordinal)
+ && sqlite3AtoF(z.ToString().Substring(8), ref r, sqlite3Strlen30(z.ToString().Substring(8)), SQLITE_UTF8)
+ && (n = (int)r) == r && n >= 0 && r < 7) {
+ sqlite3_int64 Z;
+ computeYMD_HMS(p);
+ p.validTZ = 0;
+ p.validJD = 0;
+ computeJD(p);
+ Z = ((p.iJD + 129600000) / 86400000) % 7;
+ if (Z > n)
+ Z -= 7;
+ p.iJD += (n - Z) * 86400000;
+ clearYMD_HMS_TZ(p);
+ rc = 0;
+ }
+ break;
+ }
+ case 's': {
+ /*
+ ** start of TTTTT
+ **
+ ** Move the date backwards to the beginning of the current day,
+ ** or month or year.
+ */
+ if (z.Length <= 9)
+ z.Length = 0;
+ else
+ z.Remove(0, 9);//z += 9;
+ computeYMD(p);
+ p.validHMS = 1;
+ p.h = p.m = 0;
+ p.s = 0.0;
+ p.validTZ = 0;
+ p.validJD = 0;
+ if (z.ToString() == "month") {
+ p.D = 1;
+ rc = 0;
+ } else if (z.ToString() == "year") {
+ computeYMD(p);
+ p.M = 1;
+ p.D = 1;
+ rc = 0;
+ } else if (z.ToString() == "day") {
+ rc = 0;
+ }
+ break;
+ }
+ case '+':
+ case '-':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9': {
+ double rRounder;
+ for (n = 1; n < z.Length && z[n] != ':' && !sqlite3Isspace(z[n]); n++) {
+ }
+ if (!sqlite3AtoF(z.ToString(), ref r, n, SQLITE_UTF8)) {
+ rc = 1;
+ break;
+ }
+ Debug.Assert(n >= 1);
+ if (z[n] == ':') {
+ /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
+ ** specified number of hours, minutes, seconds, and fractional seconds
+ ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
+ ** omitted.
+ */
+ string z2 = z.ToString();
+ DateTime tx;
+ sqlite3_int64 day;
+ int z2Index = 0;
+ if (!sqlite3Isdigit(z2[z2Index]))
+ z2Index++;// z2++;
+ tx = new DateTime();// memset( &tx, 0, sizeof(tx));
+ if (parseHhMmSs(z2.Substring(z2Index), tx) != 0)
+ break;
+ computeJD(tx);
+ tx.iJD -= 43200000;
+ day = tx.iJD / 86400000;
+ tx.iJD -= day * 86400000;
+ if (z[0] == '-')
+ tx.iJD = -tx.iJD;
+ computeJD(p);
+ clearYMD_HMS_TZ(p);
+ p.iJD += tx.iJD;
+ rc = 0;
+ break;
+ }
+ //z += n;
+ while (sqlite3Isspace(z[n]))
+ n++;// z++;
+ z = z.Remove(0, n);
+ n = sqlite3Strlen30(z);
+ if (n > 10 || n < 3)
+ break;
+ if (z[n - 1] == 's') {
+ z.Length = --n;
+ }// z[n - 1] = '\0'; n--; }
+ computeJD(p);
+ rc = 0;
+ rRounder = r < 0 ? -0.5 : +0.5;
+ if (n == 3 && z.ToString() == "day") {
+ p.iJD += (long)(r * 86400000.0 + rRounder);
+ } else if (n == 4 && z.ToString() == "hour") {
+ p.iJD += (long)(r * (86400000.0 / 24.0) + rRounder);
+ } else if (n == 6 && z.ToString() == "minute") {
+ p.iJD += (long)(r * (86400000.0 / (24.0 * 60.0)) + rRounder);
+ } else if (n == 6 && z.ToString() == "second") {
+ p.iJD += (long)(r * (86400000.0 / (24.0 * 60.0 * 60.0)) + rRounder);
+ } else if (n == 5 && z.ToString() == "month") {
+ int x, y;
+ computeYMD_HMS(p);
+ p.M += (int)r;
+ x = p.M > 0 ? (p.M - 1) / 12 : (p.M - 12) / 12;
+ p.Y += x;
+ p.M -= x * 12;
+ p.validJD = 0;
+ computeJD(p);
+ y = (int)r;
+ if (y != r) {
+ p.iJD += (long)((r - y) * 30.0 * 86400000.0 + rRounder);
+ }
+ } else if (n == 4 && z.ToString() == "year") {
+ int y = (int)r;
+ computeYMD_HMS(p);
+ p.Y += y;
+ p.validJD = 0;
+ computeJD(p);
+ if (y != r) {
+ p.iJD += (sqlite3_int64)((r - y) * 365.0 * 86400000.0 + rRounder);
+ }
+ } else {
+ rc = 1;
+ }
+ clearYMD_HMS_TZ(p);
+ break;
+ }
+ default: {
+ break;
+ }
}
- else if ( n == 5 && z.ToString() == "month" )
- {
- int x, y;
- computeYMD_HMS( p );
- p.M += (int)r;
- x = p.M > 0 ? ( p.M - 1 ) / 12 : ( p.M - 12 ) / 12;
- p.Y += x;
- p.M -= x * 12;
- p.validJD = 0;
- computeJD( p );
- y = (int)r;
- if ( y != r )
- {
- p.iJD += (long)( ( r - y ) * 30.0 * 86400000.0 + rRounder );
- }
- }
- else if ( n == 4 && z.ToString() == "year" )
- {
- int y = (int)r;
- computeYMD_HMS( p );
- p.Y += y;
- p.validJD = 0;
- computeJD( p );
- if ( y != r )
- {
- p.iJD += (sqlite3_int64)( ( r - y ) * 365.0 * 86400000.0 + rRounder );
- }
+ return rc;
+ }
+
+ /*
+ ** Process time function arguments. argv[0] is a date-time stamp.
+ ** argv[1] and following are modifiers. Parse them all and write
+ ** the resulting time into the DateTime structure p. Return 0
+ ** on success and 1 if there are any errors.
+ **
+ ** If there are zero parameters (if even argv[0] is undefined)
+ ** then assume a default value of "now" for argv[0].
+ */
+ static int isDate(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv,
+ ref DateTime p
+ ) {
+ int i;
+ string z;
+ int eType;
+ p = new DateTime();//memset(p, 0, sizeof(*p));
+ if (argc == 0) {
+ setDateTimeToCurrent(context, p);
+ } else if ((eType = sqlite3_value_type(argv[0])) == SQLITE_FLOAT
+ || eType == SQLITE_INTEGER) {
+ p.iJD = (long)(sqlite3_value_double(argv[0]) * 86400000.0 + 0.5);
+ p.validJD = 1;
+ } else {
+ z = sqlite3_value_text(argv[0]);
+ if (String.IsNullOrEmpty(z) || parseDateOrTime(context, z, ref p) != 0) {
+ return 1;
+ }
}
- else
- {
- rc = 1;
+ for (i = 1; i < argc; i++) {
+ z = sqlite3_value_text(argv[i]);
+ if (String.IsNullOrEmpty(z) || parseModifier(context, z, p) != 0)
+ return 1;
}
- clearYMD_HMS_TZ( p );
- break;
- }
- default:
- {
- break;
- }
- }
- return rc;
- }
-
- /*
- ** Process time function arguments. argv[0] is a date-time stamp.
- ** argv[1] and following are modifiers. Parse them all and write
- ** the resulting time into the DateTime structure p. Return 0
- ** on success and 1 if there are any errors.
- **
- ** If there are zero parameters (if even argv[0] is undefined)
- ** then assume a default value of "now" for argv[0].
- */
- static int isDate(
- sqlite3_context context,
- int argc,
- sqlite3_value[] argv,
- ref DateTime p
- )
- {
- int i;
- string z;
- int eType;
- p = new DateTime();//memset(p, 0, sizeof(*p));
- if ( argc == 0 )
- {
- setDateTimeToCurrent( context, p );
- }
- else if ( ( eType = sqlite3_value_type( argv[0] ) ) == SQLITE_FLOAT
- || eType == SQLITE_INTEGER )
- {
- p.iJD = (long)( sqlite3_value_double( argv[0] ) * 86400000.0 + 0.5 );
- p.validJD = 1;
- }
- else
- {
- z = sqlite3_value_text( argv[0] );
- if ( String.IsNullOrEmpty( z ) || parseDateOrTime( context, z, ref p ) != 0 )
- {
- return 1;
+ return 0;
}
- }
- for ( i = 1; i < argc; i++ )
- {
- z = sqlite3_value_text( argv[i] );
- if ( String.IsNullOrEmpty( z ) || parseModifier( context, z, p ) != 0 )
- return 1;
- }
- return 0;
- }
-
-
- /*
- ** The following routines implement the various date and time functions
- ** of SQLite.
- */
-
- /*
- ** julianday( TIMESTRING, MOD, MOD, ...)
- **
- ** Return the julian day number of the date specified in the arguments
- */
- static void juliandayFunc(
- sqlite3_context context,
- int argc,
- sqlite3_value[] argv
- )
- {
- DateTime x = null;
- if ( isDate( context, argc, argv, ref x ) == 0 )
- {
- computeJD( x );
- sqlite3_result_double( context, x.iJD / 86400000.0 );
- }
- }
-
- /*
- ** datetime( TIMESTRING, MOD, MOD, ...)
- **
- ** Return YYYY-MM-DD HH:MM:SS
- */
- static void datetimeFunc(
- sqlite3_context context,
- int argc,
- sqlite3_value[] argv
- )
- {
- DateTime x = null;
- if ( isDate( context, argc, argv, ref x ) == 0 )
- {
- zdtBuf.Length = 0;
- computeYMD_HMS( x );
- sqlite3_snprintf( 100, zdtBuf, "%04d-%02d-%02d %02d:%02d:%02d",
- x.Y, x.M, x.D, x.h, x.m, (int)( x.s ) );
- sqlite3_result_text( context, zdtBuf, -1, SQLITE_TRANSIENT );
- }
- }
- /*
- ** time( TIMESTRING, MOD, MOD, ...)
- **
- ** Return HH:MM:SS
- */
- static void timeFunc(
- sqlite3_context context,
- int argc,
- sqlite3_value[] argv
- )
- {
- DateTime x = new DateTime();
- if ( isDate( context, argc, argv, ref x ) == 0 )
- {
- zdtBuf.Length = 0;
- computeHMS( x );
- sqlite3_snprintf( 100, zdtBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s );
- sqlite3_result_text( context, zdtBuf, -1, SQLITE_TRANSIENT );
- }
- }
- /*
- ** date( TIMESTRING, MOD, MOD, ...)
- **
- ** Return YYYY-MM-DD
- */
- static void dateFunc(
- sqlite3_context context,
- int argc,
- sqlite3_value[] argv
- )
- {
- DateTime x = null;
- if ( isDate( context, argc, argv, ref x ) == 0 )
- {
- StringBuilder zdtBuf = new StringBuilder( 100 );
- computeYMD( x );
- sqlite3_snprintf( 100, zdtBuf, "%04d-%02d-%02d", x.Y, x.M, x.D );
- sqlite3_result_text( context, zdtBuf, -1, SQLITE_TRANSIENT );
- }
- }
+ /*
+ ** The following routines implement the various date and time functions
+ ** of SQLite.
+ */
- /*
- ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
- **
- ** Return a string described by FORMAT. Conversions as follows:
- **
- ** %d day of month
- ** %f ** fractional seconds SS.SSS
- ** %H hour 00-24
- ** %j day of year 000-366
- ** %J ** Julian day number
- ** %m month 01-12
- ** %M minute 00-59
- ** %s seconds since 1970-01-01
- ** %S seconds 00-59
- ** %w day of week 0-6 sunday==0
- ** %W week of year 00-53
- ** %Y year 0000-9999
- ** %% %
- */
- static void strftimeFunc(
- sqlite3_context context,
- int argc,
- sqlite3_value[] argv
- )
- {
- {
- DateTime x = new DateTime();
- u64 n;
- int i, j;
- StringBuilder z;
- sqlite3 db;
- string zFmt = sqlite3_value_text( argv[0] );
- StringBuilder zdtBuf = new StringBuilder( 100 );
- sqlite3_value[] argv1 = new sqlite3_value[argc - 1];
- for ( i = 0; i < argc - 1; i++ )
- {
- argv[i + 1].CopyTo( ref argv1[i] );
- }
- if ( String.IsNullOrEmpty( zFmt ) || isDate( context, argc - 1, argv1, ref x ) != 0 )
- return;
- db = sqlite3_context_db_handle( context );
- for ( i = 0, n = 1; i < zFmt.Length; i++, n++ )
- {
- if ( zFmt[i] == '%' )
- {
- switch ( (char)zFmt[i + 1] )
- {
- case 'd':
- case 'H':
- case 'm':
- case 'M':
- case 'S':
- case 'W':
- n++;
- break;
- /* fall thru */
- case 'w':
- case '%':
- break;
- case 'f':
- n += 8;
- break;
- case 'j':
- n += 3;
- break;
- case 'Y':
- n += 8;
- break;
- case 's':
- case 'J':
- n += 50;
- break;
- default:
- return; /* ERROR. return a NULL */
+ /*
+ ** julianday( TIMESTRING, MOD, MOD, ...)
+ **
+ ** Return the julian day number of the date specified in the arguments
+ */
+ static void juliandayFunc(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
+ DateTime x = null;
+ if (isDate(context, argc, argv, ref x) == 0) {
+ computeJD(x);
+ sqlite3_result_double(context, x.iJD / 86400000.0);
}
- i++;
- }
}
- testcase( n == (u64)( zdtBuf.Length - 1 ) );
- testcase( n == (u64)zdtBuf.Length );
- testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] + 1 );
- testcase( n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] );
- if ( n < (u64)zdtBuf.Capacity )
- {
- z = zdtBuf;
+
+ /*
+ ** datetime( TIMESTRING, MOD, MOD, ...)
+ **
+ ** Return YYYY-MM-DD HH:MM:SS
+ */
+ static void datetimeFunc(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
+ DateTime x = null;
+ if (isDate(context, argc, argv, ref x) == 0) {
+ zdtBuf.Length = 0;
+ computeYMD_HMS(x);
+ sqlite3_snprintf(100, zdtBuf, "%04d-%02d-%02d %02d:%02d:%02d",
+ x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
+ sqlite3_result_text(context, zdtBuf, -1, SQLITE_TRANSIENT);
+ }
}
- else if ( n > (u64)db.aLimit[SQLITE_LIMIT_LENGTH] )
- {
- sqlite3_result_error_toobig( context );
- return;
+
+ /*
+ ** time( TIMESTRING, MOD, MOD, ...)
+ **
+ ** Return HH:MM:SS
+ */
+ static void timeFunc(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
+ DateTime x = new DateTime();
+ if (isDate(context, argc, argv, ref x) == 0) {
+ zdtBuf.Length = 0;
+ computeHMS(x);
+ sqlite3_snprintf(100, zdtBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
+ sqlite3_result_text(context, zdtBuf, -1, SQLITE_TRANSIENT);
+ }
}
- else
- {
- z = new StringBuilder( (int)n );// sqlite3DbMallocRaw( db, n );
- //if ( z == 0 )
- //{
- // sqlite3_result_error_nomem( context );
- // return;
- //}
+
+ /*
+ ** date( TIMESTRING, MOD, MOD, ...)
+ **
+ ** Return YYYY-MM-DD
+ */
+ static void dateFunc(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
+ DateTime x = null;
+ if (isDate(context, argc, argv, ref x) == 0) {
+ StringBuilder zdtBuf = new StringBuilder(100);
+ computeYMD(x);
+ sqlite3_snprintf(100, zdtBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
+ sqlite3_result_text(context, zdtBuf, -1, SQLITE_TRANSIENT);
+ }
}
- computeJD( x );
- computeYMD_HMS( x );
- for ( i = j = 0; i < zFmt.Length; i++ )
- {
- if ( zFmt[i] != '%' )
- {
- z.Append( (char)zFmt[i] );
- }
- else
- {
- i++;
- zdtTemp.Length = 0;
- switch ( (char)zFmt[i] )
+
+ /*
+ ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
+ **
+ ** Return a string described by FORMAT. Conversions as follows:
+ **
+ ** %d day of month
+ ** %f ** fractional seconds SS.SSS
+ ** %H hour 00-24
+ ** %j day of year 000-366
+ ** %J ** Julian day number
+ ** %m month 01-12
+ ** %M minute 00-59
+ ** %s seconds since 1970-01-01
+ ** %S seconds 00-59
+ ** %w day of week 0-6 sunday==0
+ ** %W week of year 00-53
+ ** %Y year 0000-9999
+ ** %% %
+ */
+ static void strftimeFunc(
+ sqlite3_context context,
+ int argc,
+ sqlite3_value[] argv
+ ) {
{
- case 'd':
- sqlite3_snprintf( 3, zdtTemp, "%02d", x.D );
- z.Append( zdtTemp );
- j += 2;
- break;
- case 'f':
- {
- double s = x.s;
- if ( s > 59.999 )
- s = 59.999;
- sqlite3_snprintf( 7, zdtTemp, "%06.3f", s );
- z.Append( zdtTemp );
- j = sqlite3Strlen30( z );
- break;
+ DateTime x = new DateTime();
+ u64 n;
+ int i, j;
+ StringBuilder z;
+ sqlite3 db;
+ string zFmt = sqlite3_value_text(argv[0]);
+ StringBuilder zdtBuf = new StringBuilder(100);
+ sqlite3_value[] argv1 = new sqlite3_value[argc - 1];
+ for (i = 0; i < argc - 1; i++) {
+ argv[i + 1].CopyTo(ref argv1[i]);
}
- case 'H':
- sqlite3_snprintf( 3, zdtTemp, "%02d", x.h );
- z.Append( zdtTemp );
- j += 2;
- break;
- case 'W': /* Fall thru */
- case 'j':
- {
- int nDay; /* Number of days since 1st day of year */
- DateTime y = new DateTime();
- x.CopyTo( y );
- y.validJD = 0;
- y.M = 1;
- y.D = 1;
- computeJD( y );
- nDay = (int)( ( x.iJD - y.iJD + 43200000 ) / 86400000 );
- if ( zFmt[i] == 'W' )
- {
- int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
- wd = (int)( ( ( x.iJD + 43200000 ) / 86400000 ) % 7 );
- sqlite3_snprintf( 3, zdtTemp, "%02d", ( nDay + 7 - wd ) / 7 );
- z.Append( zdtTemp );
- j += 2;
- }
- else
- {
- sqlite3_snprintf( 4, zdtTemp, "%03d", nDay + 1 );
- z.Append( zdtTemp );
- j += 3;
- }
- break;
+ if (String.IsNullOrEmpty(zFmt) || isDate(context, argc - 1, argv1, ref x) != 0)
+ return;
+ db = sqlite3_context_db_handle(context);
+ for (i = 0, n = 1; i < zFmt.Length; i++, n++) {
+ if (zFmt[i] == '%') {
+ switch ((char)zFmt[i + 1]) {
+ case 'd':
+ case 'H':
+ case 'm':
+ case 'M':
+ case 'S':
+ case 'W':
+ n++;
+ break;
+ /* fall thru */
+ case 'w':
+ case '%':
+ break;
+ case 'f':
+ n += 8;
+ break;
+ case 'j':
+ n += 3;
+ break;
+ case 'Y':
+ n += 8;
+ break;
+ case 's':
+ case 'J':
+ n += 50;
+ break;
+ default:
+ return; /* ERROR. return a NULL */
+ }
+ i++;
+ }
}
- case 'J':
- {
- sqlite3_snprintf( 20, zdtTemp, "%.16g", x.iJD / 86400000.0 );
- z.Append( zdtTemp );
- j = sqlite3Strlen30( z );
- break;
+ testcase(n == (u64)(zdtBuf.Length - 1));
+ testcase(n == (u64)zdtBuf.Length);
+ testcase(n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH] + 1);
+ testcase(n == (u64)db.aLimit[SQLITE_LIMIT_LENGTH]);
+ if (n < (u64)zdtBuf.Capacity) {
+ z = zdtBuf;
+ } else if (n > (u64)db.aLimit[SQLITE_LIMIT_LENGTH]) {
+ sqlite3_result_error_toobig(context);
+ return;
+ } else {
+ z = new StringBuilder((int)n);// sqlite3DbMallocRaw( db, n );
+ //if ( z == 0 )
+ //{
+ // sqlite3_result_error_nomem( context );
+ // return;
+ //}
}
- case 'm':
- sqlite3_snprintf( 3, zdtTemp, "%02d", x.M );
- z.Append( zdtTemp );
- j += 2;
- break;
- case 'M':
- sqlite3_snprintf( 3, zdtTemp, "%02d", x.m );
- z.Append( zdtTemp );
- j += 2;
- break;
- case 's':
- {
- sqlite3_snprintf( 30, zdtTemp, "%lld",
- (i64)( x.iJD / 1000 - 21086676 * (i64)10000 ) );
- z.Append( zdtTemp );
- j = sqlite3Strlen30( z );
- break;
+ computeJD(x);
+ computeYMD_HMS(x);
+ for (i = j = 0; i < zFmt.Length; i++) {
+ if (zFmt[i] != '%') {
+ z.Append((char)zFmt[i]);
+ } else {
+ i++;
+ zdtTemp.Length = 0;
+ switch ((char)zFmt[i]) {
+ case 'd':
+ sqlite3_snprintf(3, zdtTemp, "%02d", x.D);
+ z.Append(zdtTemp);
+ j += 2;
+ break;
+ case 'f': {
+ double s = x.s;
+ if (s > 59.999)
+ s = 59.999;
+ sqlite3_snprintf(7, zdtTemp, "%06.3f", s);
+ z.Append(zdtTemp);
+ j = sqlite3Strlen30(z);
+ break;
+ }
+ case 'H':
+ sqlite3_snprintf(3, zdtTemp, "%02d", x.h);
+ z.Append(zdtTemp);
+ j += 2;
+ break;
+ case 'W': /* Fall thru */
+ case 'j': {
+ int nDay; /* Number of days since 1st day of year */
+ DateTime y = new DateTime();
+ x.CopyTo(y);
+ y.validJD = 0;
+ y.M = 1;
+ y.D = 1;
+ computeJD(y);
+ nDay = (int)((x.iJD - y.iJD + 43200000) / 86400000);
+ if (zFmt[i] == 'W') {
+ int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
+ wd = (int)(((x.iJD + 43200000) / 86400000) % 7);
+ sqlite3_snprintf(3, zdtTemp, "%02d", (nDay + 7 - wd) / 7);
+ z.Append(zdtTemp);
+ j += 2;
+ } else {
+ sqlite3_snprintf(4, zdtTemp, "%03d", nDay + 1);
+ z.Append(zdtTemp);
+ j += 3;
+ }
+ break;
+ }
+ case 'J': {
+ sqlite3_snprintf(20, zdtTemp, "%.16g", x.iJD / 86400000.0);
+ z.Append(zdtTemp);
+ j = sqlite3Strlen30(z);
+ break;
+ }
+ case 'm':
+ sqlite3_snprintf(3, zdtTemp, "%02d", x.M);
+ z.Append(zdtTemp);
+ j += 2;
+ break;
+ case 'M':
+ sqlite3_snprintf(3, zdtTemp, "%02d", x.m);
+ z.Append(zdtTemp);
+ j += 2;
+ break;
+ case 's': {
+ sqlite3_snprintf(30, zdtTemp, "%lld",
+ (i64)(x.iJD / 1000 - 21086676 * (i64)10000));
+ z.Append(zdtTemp);
+ j = sqlite3Strlen30(z);
+ break;
+ }
+ case 'S':
+ sqlite3_snprintf(3, zdtTemp, "%02d", (int)x.s);
+ z.Append(zdtTemp);
+ j += 2;
+ break;
+ case 'w': {
+ z.Append((((x.iJD + 129600000) / 86400000) % 7));
+ break;
+ }
+ case 'Y': {
+ sqlite3_snprintf(5, zdtTemp, "%04d", x.Y);
+ z.Append(zdtTemp);
+ j = sqlite3Strlen30(z);
+ break;
+ }
+ default:
+ z.Append('%');
+ break;
+ }
+ }
}
- case 'S':
- sqlite3_snprintf( 3, zdtTemp, "%02d", (int)x.s );
- z.Append( zdtTemp );
- j += 2;
- break;
- case 'w':
- {
- z.Append( ( ( ( x.iJD + 129600000 ) / 86400000 ) % 7 ) );
- break;
- }
- case 'Y':
- {
- sqlite3_snprintf( 5, zdtTemp, "%04d", x.Y );
- z.Append( zdtTemp );
- j = sqlite3Strlen30( z );
- break;
- }
- default:
- z.Append( '%' );
- break;
+ //z[j] = 0;
+ sqlite3_result_text(context, z, -1,
+ z == zdtBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
}
- }
}
- //z[j] = 0;
- sqlite3_result_text( context, z, -1,
- z == zdtBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC );
- }
- }
- /*
- ** current_time()
- **
- ** This function returns the same value as time('now').
- */
- static void ctimeFunc(
- sqlite3_context context,
- int NotUsed,
- sqlite3_value[] NotUsed2
- )
- {
- UNUSED_PARAMETER2( NotUsed, NotUsed2 );
- timeFunc( context, 0, null );
- }
+ /*
+ ** current_time()
+ **
+ ** This function returns the same value as time('now').
+ */
+ static void ctimeFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] NotUsed2
+ ) {
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ timeFunc(context, 0, null);
+ }
- /*
- ** current_date()
- **
- ** This function returns the same value as date('now').
- */
- static void cdateFunc(
- sqlite3_context context,
- int NotUsed,
- sqlite3_value[] NotUsed2
- )
- {
- UNUSED_PARAMETER2( NotUsed, NotUsed2 );
- dateFunc( context, 0, null );
- }
+ /*
+ ** current_date()
+ **
+ ** This function returns the same value as date('now').
+ */
+ static void cdateFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] NotUsed2
+ ) {
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ dateFunc(context, 0, null);
+ }
- /*
- ** current_timestamp()
- **
- ** This function returns the same value as datetime('now').
- */
- static void ctimestampFunc(
- sqlite3_context context,
- int NotUsed,
- sqlite3_value[] NotUsed2
- )
- {
- UNUSED_PARAMETER2( NotUsed, NotUsed2 );
- datetimeFunc( context, 0, null );
- }
+ /*
+ ** current_timestamp()
+ **
+ ** This function returns the same value as datetime('now').
+ */
+ static void ctimestampFunc(
+ sqlite3_context context,
+ int NotUsed,
+ sqlite3_value[] NotUsed2
+ ) {
+ UNUSED_PARAMETER2(NotUsed, NotUsed2);
+ datetimeFunc(context, 0, null);
+ }
#endif // * !SQLITE_OMIT_DATETIME_FUNCS) */
-#if SQLITE_OMIT_DATETIME_FUNCS
+#if SQLITE_OMIT_DATETIME_FUNCS
/*
** If the library is compiled to omit the full-scale date and time
** handling (to get a smaller binary), the following minimal version
@@ -1370,14 +1224,13 @@ sqlite3_value[] NotUsed2
#endif
- /*
-** This function registered all of the above C functions as SQL
-** functions. This should be the only routine in this file with
-** external linkage.
-*/
- static void sqlite3RegisterDateTimeFunctions()
- {
- FuncDef[] aDateTimeFuncs = new FuncDef[] {
+ /*
+ ** This function registered all of the above C functions as SQL
+ ** functions. This should be the only routine in this file with
+ ** external linkage.
+ */
+ static void sqlite3RegisterDateTimeFunctions() {
+ FuncDef[] aDateTimeFuncs = new FuncDef[] {
#if !SQLITE_OMIT_DATETIME_FUNCS
FUNCTION("julianday", -1, 0, 0, (dxFunc)juliandayFunc ),
FUNCTION("date", -1, 0, 0, (dxFunc)dateFunc ),
@@ -1393,18 +1246,17 @@ static void sqlite3RegisterDateTimeFunctions()
STR_FUNCTION("current_timestamp", 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
#endif
};
- int i;
+ int i;
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL( FuncDefHash, sqlite3GlobalFunctions );
FuncDef[] aFunc = (FuncDef)GLOBAL( FuncDef, aDateTimeFuncs );
#else
- FuncDefHash pHash = sqlite3GlobalFunctions;
- FuncDef[] aFunc = aDateTimeFuncs;
+ FuncDefHash pHash = sqlite3GlobalFunctions;
+ FuncDef[] aFunc = aDateTimeFuncs;
#endif
- for ( i = 0; i < ArraySize( aDateTimeFuncs ); i++ )
- {
- sqlite3FuncDefInsert( pHash, aFunc[i] );
- }
+ for (i = 0; i < ArraySize(aDateTimeFuncs); i++) {
+ sqlite3FuncDefInsert(pHash, aFunc[i]);
+ }
+ }
}
- }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/delete_c.cs b/Src/IronPython.SQLite/c#sqlite/delete_c.cs
index e291faa56..abf16d39d 100644
--- a/Src/IronPython.SQLite/c#sqlite/delete_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/delete_c.cs
@@ -1,152 +1,139 @@
-using System;
using System.Diagnostics;
-using System.Text;
-using u8 = System.Byte;
using u32 = System.UInt32;
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This file contains C code routines that are called by the parser
- ** in order to generate code for DELETE FROM statements.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
-
- /*
- ** While a SrcList can in general represent multiple tables and subqueries
- ** (as in the FROM clause of a SELECT statement) in this case it contains
- ** the name of a single table, as one might find in an INSERT, DELETE,
- ** or UPDATE statement. Look up that table in the symbol table and
- ** return a pointer. Set an error message and return NULL if the table
- ** name is not found or if any other error occurs.
- **
- ** The following fields are initialized appropriate in pSrc:
- **
- ** pSrc->a[0].pTab Pointer to the Table object
- ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
- **
- */
- static Table sqlite3SrcListLookup( Parse pParse, SrcList pSrc )
- {
- SrcList_item pItem = pSrc.a[0];
- Table pTab;
- Debug.Assert( pItem != null && pSrc.nSrc == 1 );
- pTab = sqlite3LocateTable( pParse, 0, pItem.zName, pItem.zDatabase );
- sqlite3DeleteTable( pParse.db, ref pItem.pTab );
- pItem.pTab = pTab;
- if ( pTab != null )
- {
- pTab.nRef++;
- }
- if ( sqlite3IndexedByLookup( pParse, pItem ) != 0 )
- {
- pTab = null;
- }
- return pTab;
- }
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains C code routines that are called by the parser
+ ** in order to generate code for DELETE FROM statements.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
+
+ /*
+ ** While a SrcList can in general represent multiple tables and subqueries
+ ** (as in the FROM clause of a SELECT statement) in this case it contains
+ ** the name of a single table, as one might find in an INSERT, DELETE,
+ ** or UPDATE statement. Look up that table in the symbol table and
+ ** return a pointer. Set an error message and return NULL if the table
+ ** name is not found or if any other error occurs.
+ **
+ ** The following fields are initialized appropriate in pSrc:
+ **
+ ** pSrc->a[0].pTab Pointer to the Table object
+ ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
+ **
+ */
+ static Table sqlite3SrcListLookup(Parse pParse, SrcList pSrc) {
+ SrcList_item pItem = pSrc.a[0];
+ Table pTab;
+ Debug.Assert(pItem != null && pSrc.nSrc == 1);
+ pTab = sqlite3LocateTable(pParse, 0, pItem.zName, pItem.zDatabase);
+ sqlite3DeleteTable(pParse.db, ref pItem.pTab);
+ pItem.pTab = pTab;
+ if (pTab != null) {
+ pTab.nRef++;
+ }
+ if (sqlite3IndexedByLookup(pParse, pItem) != 0) {
+ pTab = null;
+ }
+ return pTab;
+ }
- /*
- ** Check to make sure the given table is writable. If it is not
- ** writable, generate an error message and return 1. If it is
- ** writable return 0;
- */
- static bool sqlite3IsReadOnly( Parse pParse, Table pTab, int viewOk )
- {
- /* A table is not writable under the following circumstances:
- **
- ** 1) It is a virtual table and no implementation of the xUpdate method
- ** has been provided, or
- ** 2) It is a system table (i.e. sqlite_master), this call is not
- ** part of a nested parse and writable_schema pragma has not
- ** been specified.
- **
- ** In either case leave an error message in pParse and return non-zero.
- */
- if (
- ( IsVirtual( pTab )
- && sqlite3GetVTable( pParse.db, pTab ).pMod.pModule.xUpdate == null )
- || ( ( pTab.tabFlags & TF_Readonly ) != 0
- && ( pParse.db.flags & SQLITE_WriteSchema ) == 0
- && pParse.nested == 0 )
- )
- {
- sqlite3ErrorMsg( pParse, "table %s may not be modified", pTab.zName );
- return true;
- }
+ /*
+ ** Check to make sure the given table is writable. If it is not
+ ** writable, generate an error message and return 1. If it is
+ ** writable return 0;
+ */
+ static bool sqlite3IsReadOnly(Parse pParse, Table pTab, int viewOk) {
+ /* A table is not writable under the following circumstances:
+ **
+ ** 1) It is a virtual table and no implementation of the xUpdate method
+ ** has been provided, or
+ ** 2) It is a system table (i.e. sqlite_master), this call is not
+ ** part of a nested parse and writable_schema pragma has not
+ ** been specified.
+ **
+ ** In either case leave an error message in pParse and return non-zero.
+ */
+ if (
+ (IsVirtual(pTab)
+ && sqlite3GetVTable(pParse.db, pTab).pMod.pModule.xUpdate == null)
+ || ((pTab.tabFlags & TF_Readonly) != 0
+ && (pParse.db.flags & SQLITE_WriteSchema) == 0
+ && pParse.nested == 0)
+ ) {
+ sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab.zName);
+ return true;
+ }
#if !SQLITE_OMIT_VIEW
- if ( viewOk == 0 && pTab.pSelect != null )
- {
- sqlite3ErrorMsg( pParse, "cannot modify %s because it is a view", pTab.zName );
- return true;
- }
+ if (viewOk == 0 && pTab.pSelect != null) {
+ sqlite3ErrorMsg(pParse, "cannot modify %s because it is a view", pTab.zName);
+ return true;
+ }
#endif
- return false;
- }
+ return false;
+ }
#if !SQLITE_OMIT_VIEW && !SQLITE_OMIT_TRIGGER
- /*
-** Evaluate a view and store its result in an ephemeral table. The
-** pWhere argument is an optional WHERE clause that restricts the
-** set of rows in the view that are to be added to the ephemeral table.
-*/
- static void sqlite3MaterializeView(
- Parse pParse, /* Parsing context */
- Table pView, /* View definition */
- Expr pWhere, /* Optional WHERE clause to be added */
- int iCur /* VdbeCursor number for ephemerial table */
- )
- {
- SelectDest dest = new SelectDest();
- Select pDup;
- sqlite3 db = pParse.db;
-
- pDup = sqlite3SelectDup( db, pView.pSelect, 0 );
- if ( pWhere != null )
- {
- SrcList pFrom;
-
- pWhere = sqlite3ExprDup( db, pWhere, 0 );
- pFrom = sqlite3SrcListAppend( db, null, null, null );
- //if ( pFrom != null )
- //{
- Debug.Assert( pFrom.nSrc == 1 );
- pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName );
- pFrom.a[0].pSelect = pDup;
- Debug.Assert( pFrom.a[0].pOn == null );
- Debug.Assert( pFrom.a[0].pUsing == null );
- //}
- //else
- //{
- // sqlite3SelectDelete( db, ref pDup );
- //}
- pDup = sqlite3SelectNew( pParse, null, pFrom, pWhere, null, null, null, 0, null, null );
- }
- sqlite3SelectDestInit( dest, SRT_EphemTab, iCur );
- sqlite3Select( pParse, pDup, ref dest );
- sqlite3SelectDelete( db, ref pDup );
- }
+ /*
+ ** Evaluate a view and store its result in an ephemeral table. The
+ ** pWhere argument is an optional WHERE clause that restricts the
+ ** set of rows in the view that are to be added to the ephemeral table.
+ */
+ static void sqlite3MaterializeView(
+ Parse pParse, /* Parsing context */
+ Table pView, /* View definition */
+ Expr pWhere, /* Optional WHERE clause to be added */
+ int iCur /* VdbeCursor number for ephemerial table */
+ ) {
+ SelectDest dest = new SelectDest();
+ Select pDup;
+ sqlite3 db = pParse.db;
+
+ pDup = sqlite3SelectDup(db, pView.pSelect, 0);
+ if (pWhere != null) {
+ SrcList pFrom;
+
+ pWhere = sqlite3ExprDup(db, pWhere, 0);
+ pFrom = sqlite3SrcListAppend(db, null, null, null);
+ //if ( pFrom != null )
+ //{
+ Debug.Assert(pFrom.nSrc == 1);
+ pFrom.a[0].zAlias = pView.zName;// sqlite3DbStrDup( db, pView.zName );
+ pFrom.a[0].pSelect = pDup;
+ Debug.Assert(pFrom.a[0].pOn == null);
+ Debug.Assert(pFrom.a[0].pUsing == null);
+ //}
+ //else
+ //{
+ // sqlite3SelectDelete( db, ref pDup );
+ //}
+ pDup = sqlite3SelectNew(pParse, null, pFrom, pWhere, null, null, null, 0, null, null);
+ }
+ sqlite3SelectDestInit(dest, SRT_EphemTab, iCur);
+ sqlite3Select(pParse, pDup, ref dest);
+ sqlite3SelectDelete(db, ref pDup);
+ }
#endif //* !SQLITE_OMIT_VIEW) && !SQLITE_OMIT_TRIGGER) */
#if (SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !(SQLITE_OMIT_SUBQUERY)
@@ -244,62 +231,60 @@ char zStmtType /* Either DELETE or UPDATE. For error messages. */
}
#endif //* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
- /*
-** Generate code for a DELETE FROM statement.
-**
-** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
-** \________/ \________________/
-** pTabList pWhere
-*/
- static void sqlite3DeleteFrom(
- Parse pParse, /* The parser context */
- SrcList pTabList, /* The table from which we should delete things */
- Expr pWhere /* The WHERE clause. May be null */
- )
- {
- Vdbe v; /* The virtual database engine */
- Table pTab; /* The table from which records will be deleted */
- int end, addr = 0; /* A couple addresses of generated code */
- int i; /* Loop counter */
- WhereInfo pWInfo; /* Information about the WHERE clause */
- Index pIdx; /* For looping over indices of the table */
- int iCur; /* VDBE VdbeCursor number for pTab */
- sqlite3 db; /* Main database structure */
- AuthContext sContext; /* Authorization context */
- NameContext sNC; /* Name context to resolve expressions in */
- int iDb; /* Database number */
- int memCnt = -1; /* Memory cell used for change counting */
- int rcauth; /* Value returned by authorization callback */
+ /*
+ ** Generate code for a DELETE FROM statement.
+ **
+ ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
+ ** \________/ \________________/
+ ** pTabList pWhere
+ */
+ static void sqlite3DeleteFrom(
+ Parse pParse, /* The parser context */
+ SrcList pTabList, /* The table from which we should delete things */
+ Expr pWhere /* The WHERE clause. May be null */
+ ) {
+ Vdbe v; /* The virtual database engine */
+ Table pTab; /* The table from which records will be deleted */
+ int end, addr = 0; /* A couple addresses of generated code */
+ int i; /* Loop counter */
+ WhereInfo pWInfo; /* Information about the WHERE clause */
+ Index pIdx; /* For looping over indices of the table */
+ int iCur; /* VDBE VdbeCursor number for pTab */
+ sqlite3 db; /* Main database structure */
+ AuthContext sContext; /* Authorization context */
+ NameContext sNC; /* Name context to resolve expressions in */
+ int iDb; /* Database number */
+ int memCnt = -1; /* Memory cell used for change counting */
+ int rcauth; /* Value returned by authorization callback */
#if !SQLITE_OMIT_TRIGGER
- bool isView; /* True if attempting to delete from a view */
- Trigger pTrigger; /* List of table triggers, if required */
+ bool isView; /* True if attempting to delete from a view */
+ Trigger pTrigger; /* List of table triggers, if required */
#endif
- sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext));
-
- db = pParse.db;
- if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
- {
- goto delete_from_cleanup;
- }
- Debug.Assert( pTabList.nSrc == 1 );
-
- /* Locate the table which we want to delete. This table has to be
- ** put in an SrcList structure because some of the subroutines we
- ** will be calling are designed to work with multiple tables and expect
- ** an SrcList* parameter instead of just a Table* parameter.
- */
- pTab = sqlite3SrcListLookup( pParse, pTabList );
- if ( pTab == null )
- goto delete_from_cleanup;
-
- /* Figure out if we have any triggers and if the table being
- ** deleted from is a view
- */
+ sContext = new AuthContext();//memset(&sContext, 0, sizeof(sContext));
+
+ db = pParse.db;
+ if (pParse.nErr != 0 /*|| db.mallocFailed != 0 */ ) {
+ goto delete_from_cleanup;
+ }
+ Debug.Assert(pTabList.nSrc == 1);
+
+ /* Locate the table which we want to delete. This table has to be
+ ** put in an SrcList structure because some of the subroutines we
+ ** will be calling are designed to work with multiple tables and expect
+ ** an SrcList* parameter instead of just a Table* parameter.
+ */
+ pTab = sqlite3SrcListLookup(pParse, pTabList);
+ if (pTab == null)
+ goto delete_from_cleanup;
+
+ /* Figure out if we have any triggers and if the table being
+ ** deleted from is a view
+ */
#if !SQLITE_OMIT_TRIGGER
- int iDummy;
- pTrigger = sqlite3TriggersExist( pParse, pTab, TK_DELETE, null, out iDummy );
- isView = pTab.pSelect != null;
+ int iDummy;
+ pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, null, out iDummy);
+ isView = pTab.pSelect != null;
#else
const Trigger pTrigger = null;
bool isView = false;
@@ -309,40 +294,36 @@ Expr pWhere /* The WHERE clause. May be null */
isView = false;
#endif
- /* If pTab is really a view, make sure it has been initialized.
-*/
- if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
- {
- goto delete_from_cleanup;
- }
-
- if ( sqlite3IsReadOnly( pParse, pTab, ( pTrigger != null ? 1 : 0 ) ) )
- {
- goto delete_from_cleanup;
- }
- iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
- Debug.Assert( iDb < db.nDb );
+ /* If pTab is really a view, make sure it has been initialized.
+ */
+ if (sqlite3ViewGetColumnNames(pParse, pTab) != 0) {
+ goto delete_from_cleanup;
+ }
+
+ if (sqlite3IsReadOnly(pParse, pTab, (pTrigger != null ? 1 : 0))) {
+ goto delete_from_cleanup;
+ }
+ iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
+ Debug.Assert(iDb < db.nDb);
#if !SQLITE_OMIT_AUTHORIZATION
string zDb = db.aDb[iDb].zName; /* Name of database holding pTab */
rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
#else
- rcauth = SQLITE_OK;
+ rcauth = SQLITE_OK;
#endif
- Debug.Assert( rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE );
- if ( rcauth == SQLITE_DENY )
- {
- goto delete_from_cleanup;
- }
- Debug.Assert( !isView || pTrigger != null );
-
- /* Assign cursor number to the table and all its indices.
- */
- Debug.Assert( pTabList.nSrc == 1 );
- iCur = pTabList.a[0].iCursor = pParse.nTab++;
- for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- pParse.nTab++;
- }
+ Debug.Assert(rcauth == SQLITE_OK || rcauth == SQLITE_DENY || rcauth == SQLITE_IGNORE);
+ if (rcauth == SQLITE_DENY) {
+ goto delete_from_cleanup;
+ }
+ Debug.Assert(!isView || pTrigger != null);
+
+ /* Assign cursor number to the table and all its indices.
+ */
+ Debug.Assert(pTabList.nSrc == 1);
+ iCur = pTabList.a[0].iCursor = pParse.nTab++;
+ for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ pParse.nTab++;
+ }
#if !SQLITE_OMIT_AUTHORIZATION
/* Start the view context
@@ -351,396 +332,363 @@ Expr pWhere /* The WHERE clause. May be null */
sqlite3AuthContextPush(pParse, sContext, pTab.zName);
}
#endif
- /* Begin generating code.
-*/
- v = sqlite3GetVdbe( pParse );
- if ( v == null )
- {
- goto delete_from_cleanup;
- }
- if ( pParse.nested == 0 )
- sqlite3VdbeCountChanges( v );
- sqlite3BeginWriteOperation( pParse, 1, iDb );
-
- /* If we are trying to delete from a view, realize that view into
- ** a ephemeral table.
+ /* Begin generating code.
*/
+ v = sqlite3GetVdbe(pParse);
+ if (v == null) {
+ goto delete_from_cleanup;
+ }
+ if (pParse.nested == 0)
+ sqlite3VdbeCountChanges(v);
+ sqlite3BeginWriteOperation(pParse, 1, iDb);
+
+ /* If we are trying to delete from a view, realize that view into
+ ** a ephemeral table.
+ */
#if !(SQLITE_OMIT_VIEW) && !(SQLITE_OMIT_TRIGGER)
- if ( isView )
- {
- sqlite3MaterializeView( pParse, pTab, pWhere, iCur );
- }
+ if (isView) {
+ sqlite3MaterializeView(pParse, pTab, pWhere, iCur);
+ }
#endif
- /* Resolve the column names in the WHERE clause.
+ /* Resolve the column names in the WHERE clause.
+ */
+ sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) );
+ sNC.pParse = pParse;
+ sNC.pSrcList = pTabList;
+ if (sqlite3ResolveExprNames(sNC, ref pWhere) != 0) {
+ goto delete_from_cleanup;
+ }
+
+ /* Initialize the counter of the number of rows deleted, if
+ ** we are counting rows.
*/
- sNC = new NameContext();// memset( &sNC, 0, sizeof( sNC ) );
- sNC.pParse = pParse;
- sNC.pSrcList = pTabList;
- if ( sqlite3ResolveExprNames( sNC, ref pWhere ) != 0 )
- {
- goto delete_from_cleanup;
- }
-
- /* Initialize the counter of the number of rows deleted, if
-** we are counting rows.
-*/
- if ( ( db.flags & SQLITE_CountRows ) != 0 )
- {
- memCnt = ++pParse.nMem;
- sqlite3VdbeAddOp2( v, OP_Integer, 0, memCnt );
- }
+ if ((db.flags & SQLITE_CountRows) != 0) {
+ memCnt = ++pParse.nMem;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
+ }
#if !SQLITE_OMIT_TRUNCATE_OPTIMIZATION
- /* Special case: A DELETE without a WHERE clause deletes everything.
- ** It is easier just to erase the whole table. Prior to version 3.6.5,
- ** this optimization caused the row change count (the value returned by
- ** API function sqlite3_count_changes) to be set incorrectly. */
- if ( rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual( pTab )
- && 0 == sqlite3FkRequired( pParse, pTab, null, 0 )
- )
- {
- Debug.Assert( !isView );
- sqlite3VdbeAddOp4( v, OP_Clear, pTab.tnum, iDb, memCnt,
- pTab.zName, P4_STATIC );
- for ( pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- Debug.Assert( pIdx.pSchema == pTab.pSchema );
- sqlite3VdbeAddOp2( v, OP_Clear, pIdx.tnum, iDb );
- }
- }
- else
+ /* Special case: A DELETE without a WHERE clause deletes everything.
+ ** It is easier just to erase the whole table. Prior to version 3.6.5,
+ ** this optimization caused the row change count (the value returned by
+ ** API function sqlite3_count_changes) to be set incorrectly. */
+ if (rcauth == SQLITE_OK && pWhere == null && null == pTrigger && !IsVirtual(pTab)
+ && 0 == sqlite3FkRequired(pParse, pTab, null, 0)
+ ) {
+ Debug.Assert(!isView);
+ sqlite3VdbeAddOp4(v, OP_Clear, pTab.tnum, iDb, memCnt,
+ pTab.zName, P4_STATIC);
+ for (pIdx = pTab.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ Debug.Assert(pIdx.pSchema == pTab.pSchema);
+ sqlite3VdbeAddOp2(v, OP_Clear, pIdx.tnum, iDb);
+ }
+ } else
#endif //* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
- /* The usual case: There is a WHERE clause so we have to scan through
-** the table and pick which records to delete.
-*/
- {
- int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */
- int iRowid = ++pParse.nMem; /* Used for storing rowid values. */
- int regRowid; /* Actual register containing rowids */
-
- /* Collect rowids of every row to be deleted.
+ /* The usual case: There is a WHERE clause so we have to scan through
+ ** the table and pick which records to delete.
*/
- sqlite3VdbeAddOp2( v, OP_Null, 0, iRowSet );
- ExprList elDummy = null;
- pWInfo = sqlite3WhereBegin( pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK );
- if ( pWInfo == null )
- goto delete_from_cleanup;
- regRowid = sqlite3ExprCodeGetColumn( pParse, pTab, -1, iCur, iRowid );
- sqlite3VdbeAddOp2( v, OP_RowSetAdd, iRowSet, regRowid );
- if ( ( db.flags & SQLITE_CountRows ) != 0 )
- {
- sqlite3VdbeAddOp2( v, OP_AddImm, memCnt, 1 );
- }
-
- sqlite3WhereEnd( pWInfo );
-
- /* Delete every item whose key was written to the list during the
- ** database scan. We have to delete items after the scan is complete
- ** because deleting an item can change the scan order. */
- end = sqlite3VdbeMakeLabel( v );
-
- /* Unless this is a view, open cursors for the table we are
- ** deleting from and all its indices. If this is a view, then the
- ** only effect this statement has is to fire the INSTEAD OF
- ** triggers. */
- if ( !isView )
- {
- sqlite3OpenTableAndIndices( pParse, pTab, iCur, OP_OpenWrite );
- }
-
- addr = sqlite3VdbeAddOp3( v, OP_RowSetRead, iRowSet, end, iRowid );
-
- /* Delete the row */
+ {
+ int iRowSet = ++pParse.nMem; /* Register for rowset of rows to delete */
+ int iRowid = ++pParse.nMem; /* Used for storing rowid values. */
+ int regRowid; /* Actual register containing rowids */
+
+ /* Collect rowids of every row to be deleted.
+ */
+ sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
+ ExprList elDummy = null;
+ pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, ref elDummy, WHERE_DUPLICATES_OK);
+ if (pWInfo == null)
+ goto delete_from_cleanup;
+ regRowid = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, iRowid);
+ sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, regRowid);
+ if ((db.flags & SQLITE_CountRows) != 0) {
+ sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
+ }
+
+ sqlite3WhereEnd(pWInfo);
+
+ /* Delete every item whose key was written to the list during the
+ ** database scan. We have to delete items after the scan is complete
+ ** because deleting an item can change the scan order. */
+ end = sqlite3VdbeMakeLabel(v);
+
+ /* Unless this is a view, open cursors for the table we are
+ ** deleting from and all its indices. If this is a view, then the
+ ** only effect this statement has is to fire the INSTEAD OF
+ ** triggers. */
+ if (!isView) {
+ sqlite3OpenTableAndIndices(pParse, pTab, iCur, OP_OpenWrite);
+ }
+
+ addr = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, end, iRowid);
+
+ /* Delete the row */
#if !SQLITE_OMIT_VIRTUALTABLE
- if ( IsVirtual( pTab ) )
- {
- VTable pVTab = sqlite3GetVTable( db, pTab );
- sqlite3VtabMakeWritable( pParse, pTab );
- sqlite3VdbeAddOp4( v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB );
- sqlite3VdbeChangeP5( v, OE_Abort );
- sqlite3MayAbort( pParse );
- }
- else
+ if (IsVirtual(pTab)) {
+ VTable pVTab = sqlite3GetVTable(db, pTab);
+ sqlite3VtabMakeWritable(pParse, pTab);
+ sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iRowid, pVTab, P4_VTAB);
+ sqlite3VdbeChangeP5(v, OE_Abort);
+ sqlite3MayAbort(pParse);
+ } else
#endif
- {
- int count = ( pParse.nested == 0 ) ? 1 : 0; /* True to count changes */
- sqlite3GenerateRowDelete( pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default );
- }
-
- /* End of the delete loop */
- sqlite3VdbeAddOp2( v, OP_Goto, 0, addr );
- sqlite3VdbeResolveLabel( v, end );
-
- /* Close the cursors open on the table and its indexes. */
- if ( !isView && !IsVirtual( pTab ) )
- {
- for ( i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext )
- {
- sqlite3VdbeAddOp2( v, OP_Close, iCur + i, pIdx.tnum );
- }
- sqlite3VdbeAddOp1( v, OP_Close, iCur );
- }
- }
-
- /* Update the sqlite_sequence table by storing the content of the
- ** maximum rowid counter values recorded while inserting into
- ** autoincrement tables.
- */
- if ( pParse.nested == 0 && pParse.pTriggerTab == null )
- {
- sqlite3AutoincrementEnd( pParse );
- }
-
- /* Return the number of rows that were deleted. If this routine is
- ** generating code because of a call to sqlite3NestedParse(), do not
- ** invoke the callback function.
- */
-
- if ( ( db.flags & SQLITE_CountRows ) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab )
- {
- sqlite3VdbeAddOp2( v, OP_ResultRow, memCnt, 1 );
- sqlite3VdbeSetNumCols( v, 1 );
- sqlite3VdbeSetColName( v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC );
- }
-
-delete_from_cleanup:
+ {
+ int count = (pParse.nested == 0) ? 1 : 0; /* True to count changes */
+ sqlite3GenerateRowDelete(pParse, pTab, iCur, iRowid, count, pTrigger, OE_Default);
+ }
+
+ /* End of the delete loop */
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, addr);
+ sqlite3VdbeResolveLabel(v, end);
+
+ /* Close the cursors open on the table and its indexes. */
+ if (!isView && !IsVirtual(pTab)) {
+ for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext) {
+ sqlite3VdbeAddOp2(v, OP_Close, iCur + i, pIdx.tnum);
+ }
+ sqlite3VdbeAddOp1(v, OP_Close, iCur);
+ }
+ }
+
+ /* Update the sqlite_sequence table by storing the content of the
+ ** maximum rowid counter values recorded while inserting into
+ ** autoincrement tables.
+ */
+ if (pParse.nested == 0 && pParse.pTriggerTab == null) {
+ sqlite3AutoincrementEnd(pParse);
+ }
+
+ /* Return the number of rows that were deleted. If this routine is
+ ** generating code because of a call to sqlite3NestedParse(), do not
+ ** invoke the callback function.
+ */
+
+ if ((db.flags & SQLITE_CountRows) != 0 && 0 == pParse.nested && null == pParse.pTriggerTab) {
+ sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
+ sqlite3VdbeSetNumCols(v, 1);
+ sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
+ }
+
+ delete_from_cleanup:
#if !SQLITE_OMIT_AUTHORIZATION
sqlite3AuthContextPop(sContext);
#endif
- sqlite3SrcListDelete( db, ref pTabList );
- sqlite3ExprDelete( db, ref pWhere );
- return;
- }
-
- /* Make sure "isView" and other macros defined above are undefined. Otherwise
- ** thely may interfere with compilation of other functions in this file
- ** (or in another file, if this file becomes part of the amalgamation). */
- //#if isView
- // #undef isView
- //#endif
- //#if pTrigger
- // #undef pTrigger
- //#endif
-
- /*
- ** This routine generates VDBE code that causes a single row of a
- ** single table to be deleted.
- **
- ** The VDBE must be in a particular state when this routine is called.
- ** These are the requirements:
- **
- ** 1. A read/write cursor pointing to pTab, the table containing the row
- ** to be deleted, must be opened as cursor number $iCur.
- **
- ** 2. Read/write cursors for all indices of pTab must be open as
- ** cursor number base+i for the i-th index.
- **
- ** 3. The record number of the row to be deleted must be stored in
- ** memory cell iRowid.
- **
- ** This routine generates code to remove both the table record and all
- ** index entries that point to that record.
- */
- static void sqlite3GenerateRowDelete(
- Parse pParse, /* Parsing context */
- Table pTab, /* Table containing the row to be deleted */
- int iCur, /* VdbeCursor number for the table */
- int iRowid, /* Memory cell that contains the rowid to delete */
- int count, /* If non-zero, increment the row change counter */
- Trigger pTrigger, /* List of triggers to (potentially) fire */
- int onconf /* Default ON CONFLICT policy for triggers */
-)
- {
- Vdbe v = pParse.pVdbe; /* Vdbe */
- int iOld = 0; /* First register in OLD.* array */
- int iLabel; /* Label resolved to end of generated code */
-
- /* Vdbe is guaranteed to have been allocated by this stage. */
- Debug.Assert( v != null );
-
- /* Seek cursor iCur to the row to delete. If this row no longer exists
- ** (this can happen if a trigger program has already deleted it), do
- ** not attempt to delete it or fire any DELETE triggers. */
- iLabel = sqlite3VdbeMakeLabel( v );
- sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid );
-
- /* If there are any triggers to fire, allocate a range of registers to
- ** use for the old.* references in the triggers. */
- if ( sqlite3FkRequired( pParse, pTab, null, 0 ) != 0 || pTrigger != null )
- {
- u32 mask; /* Mask of OLD.* columns in use */
- int iCol; /* Iterator used while populating OLD.* */
-
- /* TODO: Could use temporary registers here. Also could attempt to
- ** avoid copying the contents of the rowid register. */
- mask = sqlite3TriggerColmask(
- pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf
- );
- mask |= sqlite3FkOldmask( pParse, pTab );
- iOld = pParse.nMem + 1;
- pParse.nMem += ( 1 + pTab.nCol );
-
- /* Populate the OLD.* pseudo-table register array. These values will be
- ** used by any BEFORE and AFTER triggers that exist. */
- sqlite3VdbeAddOp2( v, OP_Copy, iRowid, iOld );
- for ( iCol = 0; iCol < pTab.nCol; iCol++ )
- {
- if ( mask == 0xffffffff || ( mask & ( 1 << iCol ) ) != 0 )
- {
- sqlite3ExprCodeGetColumnOfTable( v, pTab, iCur, iCol, iOld + iCol + 1 );
- }
+ sqlite3SrcListDelete(db, ref pTabList);
+ sqlite3ExprDelete(db, ref pWhere);
+ return;
}
- /* Invoke BEFORE DELETE trigger programs. */
- sqlite3CodeRowTrigger( pParse, pTrigger,
- TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
- );
-
- /* Seek the cursor to the row to be deleted again. It may be that
- ** the BEFORE triggers coded above have already removed the row
- ** being deleted. Do not attempt to delete the row a second time, and
- ** do not fire AFTER triggers. */
- sqlite3VdbeAddOp3( v, OP_NotExists, iCur, iLabel, iRowid );
-
- /* Do FK processing. This call checks that any FK constraints that
- ** refer to this table (i.e. constraints attached to other tables)
- ** are not violated by deleting this row. */
- sqlite3FkCheck( pParse, pTab, iOld, 0 );
- }
-
- /* Delete the index and table entries. Skip this step if pTab is really
- ** a view (in which case the only effect of the DELETE statement is to
- ** fire the INSTEAD OF triggers). */
- if ( pTab.pSelect == null )
- {
- sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, 0 );
- sqlite3VdbeAddOp2( v, OP_Delete, iCur, ( count != 0 ? (int)OPFLAG_NCHANGE : 0 ) );
- if ( count != 0 )
- {
- sqlite3VdbeChangeP4( v, -1, pTab.zName, P4_TRANSIENT );
+ /* Make sure "isView" and other macros defined above are undefined. Otherwise
+ ** thely may interfere with compilation of other functions in this file
+ ** (or in another file, if this file becomes part of the amalgamation). */
+ //#if isView
+ // #undef isView
+ //#endif
+ //#if pTrigger
+ // #undef pTrigger
+ //#endif
+
+ /*
+ ** This routine generates VDBE code that causes a single row of a
+ ** single table to be deleted.
+ **
+ ** The VDBE must be in a particular state when this routine is called.
+ ** These are the requirements:
+ **
+ ** 1. A read/write cursor pointing to pTab, the table containing the row
+ ** to be deleted, must be opened as cursor number $iCur.
+ **
+ ** 2. Read/write cursors for all indices of pTab must be open as
+ ** cursor number base+i for the i-th index.
+ **
+ ** 3. The record number of the row to be deleted must be stored in
+ ** memory cell iRowid.
+ **
+ ** This routine generates code to remove both the table record and all
+ ** index entries that point to that record.
+ */
+ static void sqlite3GenerateRowDelete(
+ Parse pParse, /* Parsing context */
+ Table pTab, /* Table containing the row to be deleted */
+ int iCur, /* VdbeCursor number for the table */
+ int iRowid, /* Memory cell that contains the rowid to delete */
+ int count, /* If non-zero, increment the row change counter */
+ Trigger pTrigger, /* List of triggers to (potentially) fire */
+ int onconf /* Default ON CONFLICT policy for triggers */
+ ) {
+ Vdbe v = pParse.pVdbe; /* Vdbe */
+ int iOld = 0; /* First register in OLD.* array */
+ int iLabel; /* Label resolved to end of generated code */
+
+ /* Vdbe is guaranteed to have been allocated by this stage. */
+ Debug.Assert(v != null);
+
+ /* Seek cursor iCur to the row to delete. If this row no longer exists
+ ** (this can happen if a trigger program has already deleted it), do
+ ** not attempt to delete it or fire any DELETE triggers. */
+ iLabel = sqlite3VdbeMakeLabel(v);
+ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
+
+ /* If there are any triggers to fire, allocate a range of registers to
+ ** use for the old.* references in the triggers. */
+ if (sqlite3FkRequired(pParse, pTab, null, 0) != 0 || pTrigger != null) {
+ u32 mask; /* Mask of OLD.* columns in use */
+ int iCol; /* Iterator used while populating OLD.* */
+
+ /* TODO: Could use temporary registers here. Also could attempt to
+ ** avoid copying the contents of the rowid register. */
+ mask = sqlite3TriggerColmask(
+ pParse, pTrigger, null, 0, TRIGGER_BEFORE | TRIGGER_AFTER, pTab, onconf
+ );
+ mask |= sqlite3FkOldmask(pParse, pTab);
+ iOld = pParse.nMem + 1;
+ pParse.nMem += (1 + pTab.nCol);
+
+ /* Populate the OLD.* pseudo-table register array. These values will be
+ ** used by any BEFORE and AFTER triggers that exist. */
+ sqlite3VdbeAddOp2(v, OP_Copy, iRowid, iOld);
+ for (iCol = 0; iCol < pTab.nCol; iCol++) {
+ if (mask == 0xffffffff || (mask & (1 << iCol)) != 0) {
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iCur, iCol, iOld + iCol + 1);
+ }
+ }
+
+ /* Invoke BEFORE DELETE trigger programs. */
+ sqlite3CodeRowTrigger(pParse, pTrigger,
+ TK_DELETE, null, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
+ );
+
+ /* Seek the cursor to the row to be deleted again. It may be that
+ ** the BEFORE triggers coded above have already removed the row
+ ** being deleted. Do not attempt to delete the row a second time, and
+ ** do not fire AFTER triggers. */
+ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, iLabel, iRowid);
+
+ /* Do FK processing. This call checks that any FK constraints that
+ ** refer to this table (i.e. constraints attached to other tables)
+ ** are not violated by deleting this row. */
+ sqlite3FkCheck(pParse, pTab, iOld, 0);
+ }
+
+ /* Delete the index and table entries. Skip this step if pTab is really
+ ** a view (in which case the only effect of the DELETE statement is to
+ ** fire the INSTEAD OF triggers). */
+ if (pTab.pSelect == null) {
+ sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, 0);
+ sqlite3VdbeAddOp2(v, OP_Delete, iCur, (count != 0 ? (int)OPFLAG_NCHANGE : 0));
+ if (count != 0) {
+ sqlite3VdbeChangeP4(v, -1, pTab.zName, P4_TRANSIENT);
+ }
+ }
+
+ /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
+ ** handle rows (possibly in other tables) that refer via a foreign key
+ ** to the row just deleted. */
+ sqlite3FkActions(pParse, pTab, null, iOld);
+
+ /* Invoke AFTER DELETE trigger programs. */
+ sqlite3CodeRowTrigger(pParse, pTrigger,
+ TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
+ );
+
+ /* Jump here if the row had already been deleted before any BEFORE
+ ** trigger programs were invoked. Or if a trigger program throws a
+ ** RAISE(IGNORE) exception. */
+ sqlite3VdbeResolveLabel(v, iLabel);
}
- }
-
- /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
- ** handle rows (possibly in other tables) that refer via a foreign key
- ** to the row just deleted. */
- sqlite3FkActions( pParse, pTab, null, iOld );
-
- /* Invoke AFTER DELETE trigger programs. */
- sqlite3CodeRowTrigger( pParse, pTrigger,
- TK_DELETE, null, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
- );
-
- /* Jump here if the row had already been deleted before any BEFORE
- ** trigger programs were invoked. Or if a trigger program throws a
- ** RAISE(IGNORE) exception. */
- sqlite3VdbeResolveLabel( v, iLabel );
- }
- /*
- ** This routine generates VDBE code that causes the deletion of all
- ** index entries associated with a single row of a single table.
- **
- ** The VDBE must be in a particular state when this routine is called.
- ** These are the requirements:
- **
- ** 1. A read/write cursor pointing to pTab, the table containing the row
- ** to be deleted, must be opened as cursor number "iCur".
- **
- ** 2. Read/write cursors for all indices of pTab must be open as
- ** cursor number iCur+i for the i-th index.
- **
- ** 3. The "iCur" cursor must be pointing to the row that is to be
- ** deleted.
- */
- static void sqlite3GenerateRowIndexDelete(
- Parse pParse, /* Parsing and code generating context */
- Table pTab, /* Table containing the row to be deleted */
- int iCur, /* VdbeCursor number for the table */
- int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
- )
- {
- int[] aRegIdx = null;
- sqlite3GenerateRowIndexDelete( pParse, pTab, iCur, aRegIdx );
- }
- static void sqlite3GenerateRowIndexDelete(
- Parse pParse, /* Parsing and code generating context */
- Table pTab, /* Table containing the row to be deleted */
- int iCur, /* VdbeCursor number for the table */
- int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
- )
- {
- int i;
- Index pIdx;
- int r1;
-
- for ( i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext )
- {
- if ( aRegIdx != null && aRegIdx[i - 1] == 0 )
- continue;
- r1 = sqlite3GenerateIndexKey( pParse, pIdx, iCur, 0, false );
- sqlite3VdbeAddOp3( pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1 );
- }
- }
-
- /*
- ** Generate code that will assemble an index key and put it in register
- ** regOut. The key with be for index pIdx which is an index on pTab.
- ** iCur is the index of a cursor open on the pTab table and pointing to
- ** the entry that needs indexing.
- **
- ** Return a register number which is the first in a block of
- ** registers that holds the elements of the index key. The
- ** block of registers has already been deallocated by the time
- ** this routine returns.
- */
- static int sqlite3GenerateIndexKey(
- Parse pParse, /* Parsing context */
- Index pIdx, /* The index for which to generate a key */
- int iCur, /* VdbeCursor number for the pIdx.pTable table */
- int regOut, /* Write the new index key to this register */
- bool doMakeRec /* Run the OP_MakeRecord instruction if true */
- )
- {
- Vdbe v = pParse.pVdbe;
- int j;
- Table pTab = pIdx.pTable;
- int regBase;
- int nCol;
-
- nCol = pIdx.nColumn;
- regBase = sqlite3GetTempRange( pParse, nCol + 1 );
- sqlite3VdbeAddOp2( v, OP_Rowid, iCur, regBase + nCol );
- for ( j = 0; j < nCol; j++ )
- {
- int idx = pIdx.aiColumn[j];
- if ( idx == pTab.iPKey )
- {
- sqlite3VdbeAddOp2( v, OP_SCopy, regBase + nCol, regBase + j );
- }
- else
- {
- sqlite3VdbeAddOp3( v, OP_Column, iCur, idx, regBase + j );
- sqlite3ColumnDefault( v, pTab, idx, -1 );
+ /*
+ ** This routine generates VDBE code that causes the deletion of all
+ ** index entries associated with a single row of a single table.
+ **
+ ** The VDBE must be in a particular state when this routine is called.
+ ** These are the requirements:
+ **
+ ** 1. A read/write cursor pointing to pTab, the table containing the row
+ ** to be deleted, must be opened as cursor number "iCur".
+ **
+ ** 2. Read/write cursors for all indices of pTab must be open as
+ ** cursor number iCur+i for the i-th index.
+ **
+ ** 3. The "iCur" cursor must be pointing to the row that is to be
+ ** deleted.
+ */
+ static void sqlite3GenerateRowIndexDelete(
+ Parse pParse, /* Parsing and code generating context */
+ Table pTab, /* Table containing the row to be deleted */
+ int iCur, /* VdbeCursor number for the table */
+ int nothing /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
+ ) {
+ int[] aRegIdx = null;
+ sqlite3GenerateRowIndexDelete(pParse, pTab, iCur, aRegIdx);
}
- }
- if ( doMakeRec )
- {
- string zAff;
- if ( pTab.pSelect != null|| ( pParse.db.flags & SQLITE_IdxRealAsInt ) != 0 )
- {
- zAff = "";
+ static void sqlite3GenerateRowIndexDelete(
+ Parse pParse, /* Parsing and code generating context */
+ Table pTab, /* Table containing the row to be deleted */
+ int iCur, /* VdbeCursor number for the table */
+ int[] aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
+ ) {
+ int i;
+ Index pIdx;
+ int r1;
+
+ for (i = 1, pIdx = pTab.pIndex; pIdx != null; i++, pIdx = pIdx.pNext) {
+ if (aRegIdx != null && aRegIdx[i - 1] == 0)
+ continue;
+ r1 = sqlite3GenerateIndexKey(pParse, pIdx, iCur, 0, false);
+ sqlite3VdbeAddOp3(pParse.pVdbe, OP_IdxDelete, iCur + i, r1, pIdx.nColumn + 1);
+ }
}
- else
- {
- zAff = sqlite3IndexAffinityStr( v, pIdx );
+
+ /*
+ ** Generate code that will assemble an index key and put it in register
+ ** regOut. The key with be for index pIdx which is an index on pTab.
+ ** iCur is the index of a cursor open on the pTab table and pointing to
+ ** the entry that needs indexing.
+ **
+ ** Return a register number which is the first in a block of
+ ** registers that holds the elements of the index key. The
+ ** block of registers has already been deallocated by the time
+ ** this routine returns.
+ */
+ static int sqlite3GenerateIndexKey(
+ Parse pParse, /* Parsing context */
+ Index pIdx, /* The index for which to generate a key */
+ int iCur, /* VdbeCursor number for the pIdx.pTable table */
+ int regOut, /* Write the new index key to this register */
+ bool doMakeRec /* Run the OP_MakeRecord instruction if true */
+ ) {
+ Vdbe v = pParse.pVdbe;
+ int j;
+ Table pTab = pIdx.pTable;
+ int regBase;
+ int nCol;
+
+ nCol = pIdx.nColumn;
+ regBase = sqlite3GetTempRange(pParse, nCol + 1);
+ sqlite3VdbeAddOp2(v, OP_Rowid, iCur, regBase + nCol);
+ for (j = 0; j < nCol; j++) {
+ int idx = pIdx.aiColumn[j];
+ if (idx == pTab.iPKey) {
+ sqlite3VdbeAddOp2(v, OP_SCopy, regBase + nCol, regBase + j);
+ } else {
+ sqlite3VdbeAddOp3(v, OP_Column, iCur, idx, regBase + j);
+ sqlite3ColumnDefault(v, pTab, idx, -1);
+ }
+ }
+ if (doMakeRec) {
+ string zAff;
+ if (pTab.pSelect != null || (pParse.db.flags & SQLITE_IdxRealAsInt) != 0) {
+ zAff = "";
+ } else {
+ zAff = sqlite3IndexAffinityStr(v, pIdx);
+ }
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol + 1, regOut);
+ sqlite3VdbeChangeP4(v, -1, zAff, P4_TRANSIENT);
+ }
+ sqlite3ReleaseTempRange(pParse, regBase, nCol + 1);
+ return regBase;
}
- sqlite3VdbeAddOp3( v, OP_MakeRecord, regBase, nCol + 1, regOut );
- sqlite3VdbeChangeP4( v, -1, zAff, P4_TRANSIENT );
- }
- sqlite3ReleaseTempRange( pParse, regBase, nCol + 1 );
- return regBase;
}
- }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/expr_c.cs b/Src/IronPython.SQLite/c#sqlite/expr_c.cs
index c90409775..a8dcd7921 100644
--- a/Src/IronPython.SQLite/c#sqlite/expr_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/expr_c.cs
@@ -2,1209 +2,1061 @@
using System;
using System.Diagnostics;
-using System.Text;
-using Bitmask = System.UInt64;
using i64 = System.Int64;
using u8 = System.Byte;
using u32 = System.UInt32;
using u16 = System.UInt16;
-using Pgno = System.UInt32;
-
#if !SQLITE_MAX_VARIABLE_NUMBER
using ynVar = System.Int16;
#else
using ynVar = System.Int32;
#endif
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2001 September 15
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- **
- *************************************************************************
- ** This file contains routines used for analyzing expressions and
- ** for generating VDBE code that evaluates expressions in SQLite.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2001 September 15
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains routines used for analyzing expressions and
+ ** for generating VDBE code that evaluates expressions in SQLite.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
- /*
- ** Return the 'affinity' of the expression pExpr if any.
- **
- ** If pExpr is a column, a reference to a column via an 'AS' alias,
- ** or a sub-select with a column as the return value, then the
- ** affinity of that column is returned. Otherwise, 0x00 is returned,
- ** indicating no affinity for the expression.
- **
- ** i.e. the WHERE clause expresssions in the following statements all
- ** have an affinity:
- **
- ** CREATE TABLE t1(a);
- ** SELECT * FROM t1 WHERE a;
- ** SELECT a AS b FROM t1 WHERE b;
- ** SELECT * FROM t1 WHERE (select a from t1);
- */
- static char sqlite3ExprAffinity( Expr pExpr )
- {
- int op = pExpr.op;
- if ( op == TK_SELECT )
- {
- Debug.Assert( ( pExpr.flags & EP_xIsSelect ) != 0 );
- return sqlite3ExprAffinity( pExpr.x.pSelect.pEList.a[0].pExpr );
- }
+ /*
+ ** Return the 'affinity' of the expression pExpr if any.
+ **
+ ** If pExpr is a column, a reference to a column via an 'AS' alias,
+ ** or a sub-select with a column as the return value, then the
+ ** affinity of that column is returned. Otherwise, 0x00 is returned,
+ ** indicating no affinity for the expression.
+ **
+ ** i.e. the WHERE clause expresssions in the following statements all
+ ** have an affinity:
+ **
+ ** CREATE TABLE t1(a);
+ ** SELECT * FROM t1 WHERE a;
+ ** SELECT a AS b FROM t1 WHERE b;
+ ** SELECT * FROM t1 WHERE (select a from t1);
+ */
+ static char sqlite3ExprAffinity(Expr pExpr) {
+ int op = pExpr.op;
+ if (op == TK_SELECT) {
+ Debug.Assert((pExpr.flags & EP_xIsSelect) != 0);
+ return sqlite3ExprAffinity(pExpr.x.pSelect.pEList.a[0].pExpr);
+ }
#if !SQLITE_OMIT_CAST
- if ( op == TK_CAST )
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- return sqlite3AffinityType( pExpr.u.zToken );
- }
+ if (op == TK_CAST) {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ return sqlite3AffinityType(pExpr.u.zToken);
+ }
#endif
- if ( ( op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER )
- && pExpr.pTab != null
- )
- {
- /* op==TK_REGISTER && pExpr.pTab!=0 happens when pExpr was originally
- ** a TK_COLUMN but was previously evaluated and cached in a register */
- int j = pExpr.iColumn;
- if ( j < 0 )
- return SQLITE_AFF_INTEGER;
- Debug.Assert( pExpr.pTab != null && j < pExpr.pTab.nCol );
- return pExpr.pTab.aCol[j].affinity;
- }
- return pExpr.affinity;
- }
-
- /*
- ** Set the explicit collating sequence for an expression to the
- ** collating sequence supplied in the second argument.
- */
- static Expr sqlite3ExprSetColl( Expr pExpr, CollSeq pColl )
- {
- if ( pExpr != null && pColl != null )
- {
- pExpr.pColl = pColl;
- pExpr.flags |= EP_ExpCollate;
- }
- return pExpr;
- }
+ if ((op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER)
+ && pExpr.pTab != null
+ ) {
+ /* op==TK_REGISTER && pExpr.pTab!=0 happens when pExpr was originally
+ ** a TK_COLUMN but was previously evaluated and cached in a register */
+ int j = pExpr.iColumn;
+ if (j < 0)
+ return SQLITE_AFF_INTEGER;
+ Debug.Assert(pExpr.pTab != null && j < pExpr.pTab.nCol);
+ return pExpr.pTab.aCol[j].affinity;
+ }
+ return pExpr.affinity;
+ }
- /*
- ** Set the collating sequence for expression pExpr to be the collating
- ** sequence named by pToken. Return a pointer to the revised expression.
- ** The collating sequence is marked as "explicit" using the EP_ExpCollate
- ** flag. An explicit collating sequence will override implicit
- ** collating sequences.
- */
- static Expr sqlite3ExprSetCollByToken( Parse pParse, Expr pExpr, Token pCollName )
- {
- string zColl; /* Dequoted name of collation sequence */
- CollSeq pColl;
- sqlite3 db = pParse.db;
- zColl = sqlite3NameFromToken( db, pCollName );
- pColl = sqlite3LocateCollSeq( pParse, zColl );
- sqlite3ExprSetColl( pExpr, pColl );
- sqlite3DbFree( db, ref zColl );
- return pExpr;
- }
+ /*
+ ** Set the explicit collating sequence for an expression to the
+ ** collating sequence supplied in the second argument.
+ */
+ static Expr sqlite3ExprSetColl(Expr pExpr, CollSeq pColl) {
+ if (pExpr != null && pColl != null) {
+ pExpr.pColl = pColl;
+ pExpr.flags |= EP_ExpCollate;
+ }
+ return pExpr;
+ }
- /*
- ** Return the default collation sequence for the expression pExpr. If
- ** there is no default collation type, return 0.
- */
- static CollSeq sqlite3ExprCollSeq( Parse pParse, Expr pExpr )
- {
- CollSeq pColl = null;
- Expr p = pExpr;
- while ( ALWAYS( p ) )
- {
- int op;
- pColl = pExpr.pColl;
- if ( pColl != null )
- break;
- op = p.op;
- if ( p.pTab != null && (
- op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER || op == TK_TRIGGER
- ) )
- {
- /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
- ** a TK_COLUMN but was previously evaluated and cached in a register */
- string zColl;
- int j = p.iColumn;
- if ( j >= 0 )
- {
+ /*
+ ** Set the collating sequence for expression pExpr to be the collating
+ ** sequence named by pToken. Return a pointer to the revised expression.
+ ** The collating sequence is marked as "explicit" using the EP_ExpCollate
+ ** flag. An explicit collating sequence will override implicit
+ ** collating sequences.
+ */
+ static Expr sqlite3ExprSetCollByToken(Parse pParse, Expr pExpr, Token pCollName) {
+ string zColl; /* Dequoted name of collation sequence */
+ CollSeq pColl;
sqlite3 db = pParse.db;
- zColl = p.pTab.aCol[j].zColl;
- pColl = sqlite3FindCollSeq( db, ENC( db ), zColl, 0 );
- pExpr.pColl = pColl;
- }
- break;
- }
- if ( op != TK_CAST && op != TK_UPLUS )
- {
- break;
+ zColl = sqlite3NameFromToken(db, pCollName);
+ pColl = sqlite3LocateCollSeq(pParse, zColl);
+ sqlite3ExprSetColl(pExpr, pColl);
+ sqlite3DbFree(db, ref zColl);
+ return pExpr;
}
- p = p.pLeft;
- }
- if ( sqlite3CheckCollSeq( pParse, pColl ) != 0 )
- {
- pColl = null;
- }
- return pColl;
- }
- /*
- ** pExpr is an operand of a comparison operator. aff2 is the
- ** type affinity of the other operand. This routine returns the
- ** type affinity that should be used for the comparison operator.
- */
- static char sqlite3CompareAffinity( Expr pExpr, char aff2 )
- {
- char aff1 = sqlite3ExprAffinity( pExpr );
- if ( aff1 != '\0' && aff2 != '\0' )
- {
- /* Both sides of the comparison are columns. If one has numeric
- ** affinity, use that. Otherwise use no affinity.
+ /*
+ ** Return the default collation sequence for the expression pExpr. If
+ ** there is no default collation type, return 0.
*/
- if ( aff1 >= SQLITE_AFF_NUMERIC || aff2 >= SQLITE_AFF_NUMERIC )
- // if (sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2))
- {
- return SQLITE_AFF_NUMERIC;
- }
- else
- {
- return SQLITE_AFF_NONE;
+ static CollSeq sqlite3ExprCollSeq(Parse pParse, Expr pExpr) {
+ CollSeq pColl = null;
+ Expr p = pExpr;
+ while (ALWAYS(p)) {
+ int op;
+ pColl = pExpr.pColl;
+ if (pColl != null)
+ break;
+ op = p.op;
+ if (p.pTab != null && (
+ op == TK_AGG_COLUMN || op == TK_COLUMN || op == TK_REGISTER || op == TK_TRIGGER
+ )) {
+ /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
+ ** a TK_COLUMN but was previously evaluated and cached in a register */
+ string zColl;
+ int j = p.iColumn;
+ if (j >= 0) {
+ sqlite3 db = pParse.db;
+ zColl = p.pTab.aCol[j].zColl;
+ pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
+ pExpr.pColl = pColl;
+ }
+ break;
+ }
+ if (op != TK_CAST && op != TK_UPLUS) {
+ break;
+ }
+ p = p.pLeft;
+ }
+ if (sqlite3CheckCollSeq(pParse, pColl) != 0) {
+ pColl = null;
+ }
+ return pColl;
}
- }
- else if ( aff1 == '\0' && aff2 == '\0' )
- {
- /* Neither side of the comparison is a column. Compare the
- ** results directly.
+
+ /*
+ ** pExpr is an operand of a comparison operator. aff2 is the
+ ** type affinity of the other operand. This routine returns the
+ ** type affinity that should be used for the comparison operator.
*/
- return SQLITE_AFF_NONE;
- }
- else
- {
- /* One side is a column, the other is not. Use the columns affinity. */
- Debug.Assert( aff1 == 0 || aff2 == 0 );
- return ( aff1 != '\0' ? aff1 : aff2 );
- }
- }
+ static char sqlite3CompareAffinity(Expr pExpr, char aff2) {
+ char aff1 = sqlite3ExprAffinity(pExpr);
+ if (aff1 != '\0' && aff2 != '\0') {
+ /* Both sides of the comparison are columns. If one has numeric
+ ** affinity, use that. Otherwise use no affinity.
+ */
+ if (aff1 >= SQLITE_AFF_NUMERIC || aff2 >= SQLITE_AFF_NUMERIC)
+ // if (sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2))
+ {
+ return SQLITE_AFF_NUMERIC;
+ } else {
+ return SQLITE_AFF_NONE;
+ }
+ } else if (aff1 == '\0' && aff2 == '\0') {
+ /* Neither side of the comparison is a column. Compare the
+ ** results directly.
+ */
+ return SQLITE_AFF_NONE;
+ } else {
+ /* One side is a column, the other is not. Use the columns affinity. */
+ Debug.Assert(aff1 == 0 || aff2 == 0);
+ return (aff1 != '\0' ? aff1 : aff2);
+ }
+ }
- /*
- ** pExpr is a comparison operator. Return the type affinity that should
- ** be applied to both operands prior to doing the comparison.
- */
- static char comparisonAffinity( Expr pExpr )
- {
- char aff;
- Debug.Assert( pExpr.op == TK_EQ || pExpr.op == TK_IN || pExpr.op == TK_LT ||
- pExpr.op == TK_GT || pExpr.op == TK_GE || pExpr.op == TK_LE ||
- pExpr.op == TK_NE || pExpr.op == TK_IS || pExpr.op == TK_ISNOT );
- Debug.Assert( pExpr.pLeft != null );
- aff = sqlite3ExprAffinity( pExpr.pLeft );
- if ( pExpr.pRight != null )
- {
- aff = sqlite3CompareAffinity( pExpr.pRight, aff );
- }
- else if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
- {
- aff = sqlite3CompareAffinity( pExpr.x.pSelect.pEList.a[0].pExpr, aff );
- }
- else if ( aff == '\0' )
- {
- aff = SQLITE_AFF_NONE;
- }
- return aff;
- }
+ /*
+ ** pExpr is a comparison operator. Return the type affinity that should
+ ** be applied to both operands prior to doing the comparison.
+ */
+ static char comparisonAffinity(Expr pExpr) {
+ char aff;
+ Debug.Assert(pExpr.op == TK_EQ || pExpr.op == TK_IN || pExpr.op == TK_LT ||
+ pExpr.op == TK_GT || pExpr.op == TK_GE || pExpr.op == TK_LE ||
+ pExpr.op == TK_NE || pExpr.op == TK_IS || pExpr.op == TK_ISNOT);
+ Debug.Assert(pExpr.pLeft != null);
+ aff = sqlite3ExprAffinity(pExpr.pLeft);
+ if (pExpr.pRight != null) {
+ aff = sqlite3CompareAffinity(pExpr.pRight, aff);
+ } else if (ExprHasProperty(pExpr, EP_xIsSelect)) {
+ aff = sqlite3CompareAffinity(pExpr.x.pSelect.pEList.a[0].pExpr, aff);
+ } else if (aff == '\0') {
+ aff = SQLITE_AFF_NONE;
+ }
+ return aff;
+ }
- /*
- ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
- ** idx_affinity is the affinity of an indexed column. Return true
- ** if the index with affinity idx_affinity may be used to implement
- ** the comparison in pExpr.
- */
- static bool sqlite3IndexAffinityOk( Expr pExpr, char idx_affinity )
- {
- char aff = comparisonAffinity( pExpr );
- switch ( aff )
- {
- case SQLITE_AFF_NONE:
- return true;
- case SQLITE_AFF_TEXT:
- return idx_affinity == SQLITE_AFF_TEXT;
- default:
- return idx_affinity >= SQLITE_AFF_NUMERIC;// sqlite3IsNumericAffinity(idx_affinity);
- }
- }
+ /*
+ ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
+ ** idx_affinity is the affinity of an indexed column. Return true
+ ** if the index with affinity idx_affinity may be used to implement
+ ** the comparison in pExpr.
+ */
+ static bool sqlite3IndexAffinityOk(Expr pExpr, char idx_affinity) {
+ char aff = comparisonAffinity(pExpr);
+ switch (aff) {
+ case SQLITE_AFF_NONE:
+ return true;
+ case SQLITE_AFF_TEXT:
+ return idx_affinity == SQLITE_AFF_TEXT;
+ default:
+ return idx_affinity >= SQLITE_AFF_NUMERIC;// sqlite3IsNumericAffinity(idx_affinity);
+ }
+ }
- /*
- ** Return the P5 value that should be used for a binary comparison
- ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
- */
- static u8 binaryCompareP5( Expr pExpr1, Expr pExpr2, int jumpIfNull )
- {
- u8 aff = (u8)sqlite3ExprAffinity( pExpr2 );
- aff = (u8)( (u8)sqlite3CompareAffinity( pExpr1, (char)aff ) | (u8)jumpIfNull );
- return aff;
- }
+ /*
+ ** Return the P5 value that should be used for a binary comparison
+ ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
+ */
+ static u8 binaryCompareP5(Expr pExpr1, Expr pExpr2, int jumpIfNull) {
+ u8 aff = (u8)sqlite3ExprAffinity(pExpr2);
+ aff = (u8)((u8)sqlite3CompareAffinity(pExpr1, (char)aff) | (u8)jumpIfNull);
+ return aff;
+ }
- /*
- ** Return a pointer to the collation sequence that should be used by
- ** a binary comparison operator comparing pLeft and pRight.
- **
- ** If the left hand expression has a collating sequence type, then it is
- ** used. Otherwise the collation sequence for the right hand expression
- ** is used, or the default (BINARY) if neither expression has a collating
- ** type.
- **
- ** Argument pRight (but not pLeft) may be a null pointer. In this case,
- ** it is not considered.
- */
- static CollSeq sqlite3BinaryCompareCollSeq(
- Parse pParse,
- Expr pLeft,
- Expr pRight
- )
- {
- CollSeq pColl;
- Debug.Assert( pLeft != null );
- if ( ( pLeft.flags & EP_ExpCollate ) != 0 )
- {
- Debug.Assert( pLeft.pColl != null );
- pColl = pLeft.pColl;
- }
- else if ( pRight != null && ( ( pRight.flags & EP_ExpCollate ) != 0 ) )
- {
- Debug.Assert( pRight.pColl != null );
- pColl = pRight.pColl;
- }
- else
- {
- pColl = sqlite3ExprCollSeq( pParse, pLeft );
- if ( pColl == null )
- {
- pColl = sqlite3ExprCollSeq( pParse, pRight );
+ /*
+ ** Return a pointer to the collation sequence that should be used by
+ ** a binary comparison operator comparing pLeft and pRight.
+ **
+ ** If the left hand expression has a collating sequence type, then it is
+ ** used. Otherwise the collation sequence for the right hand expression
+ ** is used, or the default (BINARY) if neither expression has a collating
+ ** type.
+ **
+ ** Argument pRight (but not pLeft) may be a null pointer. In this case,
+ ** it is not considered.
+ */
+ static CollSeq sqlite3BinaryCompareCollSeq(
+ Parse pParse,
+ Expr pLeft,
+ Expr pRight
+ ) {
+ CollSeq pColl;
+ Debug.Assert(pLeft != null);
+ if ((pLeft.flags & EP_ExpCollate) != 0) {
+ Debug.Assert(pLeft.pColl != null);
+ pColl = pLeft.pColl;
+ } else if (pRight != null && ((pRight.flags & EP_ExpCollate) != 0)) {
+ Debug.Assert(pRight.pColl != null);
+ pColl = pRight.pColl;
+ } else {
+ pColl = sqlite3ExprCollSeq(pParse, pLeft);
+ if (pColl == null) {
+ pColl = sqlite3ExprCollSeq(pParse, pRight);
+ }
+ }
+ return pColl;
}
- }
- return pColl;
- }
- /*
- ** Generate code for a comparison operator.
- */
- static int codeCompare(
- Parse pParse, /* The parsing (and code generating) context */
- Expr pLeft, /* The left operand */
- Expr pRight, /* The right operand */
- int opcode, /* The comparison opcode */
- int in1, int in2, /* Register holding operands */
- int dest, /* Jump here if true. */
- int jumpIfNull /* If true, jump if either operand is NULL */
- )
- {
- int p5;
- int addr;
- CollSeq p4;
-
- p4 = sqlite3BinaryCompareCollSeq( pParse, pLeft, pRight );
- p5 = binaryCompareP5( pLeft, pRight, jumpIfNull );
- addr = sqlite3VdbeAddOp4( pParse.pVdbe, opcode, in2, dest, in1,
- p4, P4_COLLSEQ );
- sqlite3VdbeChangeP5( pParse.pVdbe, (u8)p5 );
- return addr;
- }
+ /*
+ ** Generate code for a comparison operator.
+ */
+ static int codeCompare(
+ Parse pParse, /* The parsing (and code generating) context */
+ Expr pLeft, /* The left operand */
+ Expr pRight, /* The right operand */
+ int opcode, /* The comparison opcode */
+ int in1, int in2, /* Register holding operands */
+ int dest, /* Jump here if true. */
+ int jumpIfNull /* If true, jump if either operand is NULL */
+ ) {
+ int p5;
+ int addr;
+ CollSeq p4;
+
+ p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
+ p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
+ addr = sqlite3VdbeAddOp4(pParse.pVdbe, opcode, in2, dest, in1,
+ p4, P4_COLLSEQ);
+ sqlite3VdbeChangeP5(pParse.pVdbe, (u8)p5);
+ return addr;
+ }
#if SQLITE_MAX_EXPR_DEPTH //>0
- /*
-** Check that argument nHeight is less than or equal to the maximum
-** expression depth allowed. If it is not, leave an error message in
-** pParse.
-*/
- static int sqlite3ExprCheckHeight( Parse pParse, int nHeight )
- {
- int rc = SQLITE_OK;
- int mxHeight = pParse.db.aLimit[SQLITE_LIMIT_EXPR_DEPTH];
- if ( nHeight > mxHeight )
- {
- sqlite3ErrorMsg( pParse,
- "Expression tree is too large (maximum depth %d)", mxHeight
- );
- rc = SQLITE_ERROR;
- }
- return rc;
- }
+ /*
+ ** Check that argument nHeight is less than or equal to the maximum
+ ** expression depth allowed. If it is not, leave an error message in
+ ** pParse.
+ */
+ static int sqlite3ExprCheckHeight(Parse pParse, int nHeight) {
+ int rc = SQLITE_OK;
+ int mxHeight = pParse.db.aLimit[SQLITE_LIMIT_EXPR_DEPTH];
+ if (nHeight > mxHeight) {
+ sqlite3ErrorMsg(pParse,
+ "Expression tree is too large (maximum depth %d)", mxHeight
+ );
+ rc = SQLITE_ERROR;
+ }
+ return rc;
+ }
- /* The following three functions, heightOfExpr(), heightOfExprList()
- ** and heightOfSelect(), are used to determine the maximum height
- ** of any expression tree referenced by the structure passed as the
- ** first argument.
- **
- ** If this maximum height is greater than the current value pointed
- ** to by pnHeight, the second parameter, then set pnHeight to that
- ** value.
- */
- static void heightOfExpr( Expr p, ref int pnHeight )
- {
- if ( p != null )
- {
- if ( p.nHeight > pnHeight )
- {
- pnHeight = p.nHeight;
+ /* The following three functions, heightOfExpr(), heightOfExprList()
+ ** and heightOfSelect(), are used to determine the maximum height
+ ** of any expression tree referenced by the structure passed as the
+ ** first argument.
+ **
+ ** If this maximum height is greater than the current value pointed
+ ** to by pnHeight, the second parameter, then set pnHeight to that
+ ** value.
+ */
+ static void heightOfExpr(Expr p, ref int pnHeight) {
+ if (p != null) {
+ if (p.nHeight > pnHeight) {
+ pnHeight = p.nHeight;
+ }
+ }
}
- }
- }
- static void heightOfExprList( ExprList p, ref int pnHeight )
- {
- if ( p != null )
- {
- int i;
- for ( i = 0; i < p.nExpr; i++ )
- {
- heightOfExpr( p.a[i].pExpr, ref pnHeight );
+ static void heightOfExprList(ExprList p, ref int pnHeight) {
+ if (p != null) {
+ int i;
+ for (i = 0; i < p.nExpr; i++) {
+ heightOfExpr(p.a[i].pExpr, ref pnHeight);
+ }
+ }
+ }
+ static void heightOfSelect(Select p, ref int pnHeight) {
+ if (p != null) {
+ heightOfExpr(p.pWhere, ref pnHeight);
+ heightOfExpr(p.pHaving, ref pnHeight);
+ heightOfExpr(p.pLimit, ref pnHeight);
+ heightOfExpr(p.pOffset, ref pnHeight);
+ heightOfExprList(p.pEList, ref pnHeight);
+ heightOfExprList(p.pGroupBy, ref pnHeight);
+ heightOfExprList(p.pOrderBy, ref pnHeight);
+ heightOfSelect(p.pPrior, ref pnHeight);
+ }
}
- }
- }
- static void heightOfSelect( Select p, ref int pnHeight )
- {
- if ( p != null )
- {
- heightOfExpr( p.pWhere, ref pnHeight );
- heightOfExpr( p.pHaving, ref pnHeight );
- heightOfExpr( p.pLimit, ref pnHeight );
- heightOfExpr( p.pOffset, ref pnHeight );
- heightOfExprList( p.pEList, ref pnHeight );
- heightOfExprList( p.pGroupBy, ref pnHeight );
- heightOfExprList( p.pOrderBy, ref pnHeight );
- heightOfSelect( p.pPrior, ref pnHeight );
- }
- }
- /*
- ** Set the Expr.nHeight variable in the structure passed as an
- ** argument. An expression with no children, Expr.x.pList or
- ** Expr.x.pSelect member has a height of 1. Any other expression
- ** has a height equal to the maximum height of any other
- ** referenced Expr plus one.
- */
- static void exprSetHeight( Expr p )
- {
- int nHeight = 0;
- heightOfExpr( p.pLeft, ref nHeight );
- heightOfExpr( p.pRight, ref nHeight );
- if ( ExprHasProperty( p, EP_xIsSelect ) )
- {
- heightOfSelect( p.x.pSelect, ref nHeight );
- }
- else
- {
- heightOfExprList( p.x.pList, ref nHeight );
- }
- p.nHeight = nHeight + 1;
- }
+ /*
+ ** Set the Expr.nHeight variable in the structure passed as an
+ ** argument. An expression with no children, Expr.x.pList or
+ ** Expr.x.pSelect member has a height of 1. Any other expression
+ ** has a height equal to the maximum height of any other
+ ** referenced Expr plus one.
+ */
+ static void exprSetHeight(Expr p) {
+ int nHeight = 0;
+ heightOfExpr(p.pLeft, ref nHeight);
+ heightOfExpr(p.pRight, ref nHeight);
+ if (ExprHasProperty(p, EP_xIsSelect)) {
+ heightOfSelect(p.x.pSelect, ref nHeight);
+ } else {
+ heightOfExprList(p.x.pList, ref nHeight);
+ }
+ p.nHeight = nHeight + 1;
+ }
- /*
- ** Set the Expr.nHeight variable using the exprSetHeight() function. If
- ** the height is greater than the maximum allowed expression depth,
- ** leave an error in pParse.
- */
- static void sqlite3ExprSetHeight( Parse pParse, Expr p )
- {
- exprSetHeight( p );
- sqlite3ExprCheckHeight( pParse, p.nHeight );
- }
+ /*
+ ** Set the Expr.nHeight variable using the exprSetHeight() function. If
+ ** the height is greater than the maximum allowed expression depth,
+ ** leave an error in pParse.
+ */
+ static void sqlite3ExprSetHeight(Parse pParse, Expr p) {
+ exprSetHeight(p);
+ sqlite3ExprCheckHeight(pParse, p.nHeight);
+ }
- /*
- ** Return the maximum height of any expression tree referenced
- ** by the select statement passed as an argument.
- */
- static int sqlite3SelectExprHeight( Select p )
- {
- int nHeight = 0;
- heightOfSelect( p, ref nHeight );
- return nHeight;
- }
+ /*
+ ** Return the maximum height of any expression tree referenced
+ ** by the select statement passed as an argument.
+ */
+ static int sqlite3SelectExprHeight(Select p) {
+ int nHeight = 0;
+ heightOfSelect(p, ref nHeight);
+ return nHeight;
+ }
#else
//#define exprSetHeight(y)
#endif //* SQLITE_MAX_EXPR_DEPTH>0 */
- /*
-** This routine is the core allocator for Expr nodes.
-**
-** Construct a new expression node and return a pointer to it. Memory
-** for this node and for the pToken argument is a single allocation
-** obtained from sqlite3DbMalloc(). The calling function
-** is responsible for making sure the node eventually gets freed.
-**
-** If dequote is true, then the token (if it exists) is dequoted.
-** If dequote is false, no dequoting is performance. The deQuote
-** parameter is ignored if pToken is NULL or if the token does not
-** appear to be quoted. If the quotes were of the form "..." (double-quotes)
-** then the EP_DblQuoted flag is set on the expression node.
-**
-** Special case: If op==TK_INTEGER and pToken points to a string that
-** can be translated into a 32-bit integer, then the token is not
-** stored in u.zToken. Instead, the integer values is written
-** into u.iValue and the EP_IntValue flag is set. No extra storage
-** is allocated to hold the integer text and the dequote flag is ignored.
-*/
- static Expr sqlite3ExprAlloc(
- sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */
- int op, /* Expression opcode */
- Token pToken, /* Token argument. Might be NULL */
- int dequote /* True to dequote */
- )
- {
- Expr pNew;
- int nExtra = 0;
- int iValue = 0;
-
- if ( pToken != null )
- {
- if ( op != TK_INTEGER || pToken.z == null || pToken.z.Length == 0
- || sqlite3GetInt32( pToken.z.ToString(), ref iValue ) == false )
- {
- nExtra = pToken.n + 1;
- Debug.Assert( iValue >= 0 );
- }
- }
- pNew = new Expr();//sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
- if ( pNew != null )
- {
- pNew.op = (u8)op;
- pNew.iAgg = -1;
- if ( pToken != null )
- {
- if ( nExtra == 0 )
- {
- pNew.flags |= EP_IntValue;
- pNew.u.iValue = iValue;
- }
- else
- {
- int c;
- //pNew.u.zToken = (char)&pNew[1];
- if ( pToken.n > 0 )
- pNew.u.zToken = pToken.z.Substring( 0, pToken.n );//memcpy(pNew.u.zToken, pToken.z, pToken.n);
- else if ( pToken.n == 0 && string.IsNullOrEmpty(pToken.z))
- pNew.u.zToken = string.Empty;
- //pNew.u.zToken[pToken.n] = 0;
- if ( dequote != 0 && nExtra >= 3
- && ( ( c = pToken.z[0] ) == '\'' || c == '"' || c == '[' || c == '`' ) )
- {
+ /*
+ ** This routine is the core allocator for Expr nodes.
+ **
+ ** Construct a new expression node and return a pointer to it. Memory
+ ** for this node and for the pToken argument is a single allocation
+ ** obtained from sqlite3DbMalloc(). The calling function
+ ** is responsible for making sure the node eventually gets freed.
+ **
+ ** If dequote is true, then the token (if it exists) is dequoted.
+ ** If dequote is false, no dequoting is performance. The deQuote
+ ** parameter is ignored if pToken is NULL or if the token does not
+ ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
+ ** then the EP_DblQuoted flag is set on the expression node.
+ **
+ ** Special case: If op==TK_INTEGER and pToken points to a string that
+ ** can be translated into a 32-bit integer, then the token is not
+ ** stored in u.zToken. Instead, the integer values is written
+ ** into u.iValue and the EP_IntValue flag is set. No extra storage
+ ** is allocated to hold the integer text and the dequote flag is ignored.
+ */
+ static Expr sqlite3ExprAlloc(
+ sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */
+ int op, /* Expression opcode */
+ Token pToken, /* Token argument. Might be NULL */
+ int dequote /* True to dequote */
+ ) {
+ Expr pNew;
+ int nExtra = 0;
+ int iValue = 0;
+
+ if (pToken != null) {
+ if (op != TK_INTEGER || pToken.z == null || pToken.z.Length == 0
+ || sqlite3GetInt32(pToken.z.ToString(), ref iValue) == false) {
+ nExtra = pToken.n + 1;
+ Debug.Assert(iValue >= 0);
+ }
+ }
+ pNew = new Expr();//sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
+ if (pNew != null) {
+ pNew.op = (u8)op;
+ pNew.iAgg = -1;
+ if (pToken != null) {
+ if (nExtra == 0) {
+ pNew.flags |= EP_IntValue;
+ pNew.u.iValue = iValue;
+ } else {
+ int c;
+ //pNew.u.zToken = (char)&pNew[1];
+ if (pToken.n > 0)
+ pNew.u.zToken = pToken.z.Substring(0, pToken.n);//memcpy(pNew.u.zToken, pToken.z, pToken.n);
+ else if (pToken.n == 0 && string.IsNullOrEmpty(pToken.z))
+ pNew.u.zToken = string.Empty;
+ //pNew.u.zToken[pToken.n] = 0;
+ if (dequote != 0 && nExtra >= 3
+ && ((c = pToken.z[0]) == '\'' || c == '"' || c == '[' || c == '`')) {
#if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL
sqlite3Dequote(ref pNew.u._zToken);
#else
- sqlite3Dequote( ref pNew.u.zToken );
+ sqlite3Dequote(ref pNew.u.zToken);
#endif
- if ( c == '"' )
- pNew.flags |= EP_DblQuoted;
- }
- }
- }
+ if (c == '"')
+ pNew.flags |= EP_DblQuoted;
+ }
+ }
+ }
#if SQLITE_MAX_EXPR_DEPTH//>0
- pNew.nHeight = 1;
+ pNew.nHeight = 1;
#endif
- }
- return pNew;
- }
-
- /*
- ** Allocate a new expression node from a zero-terminated token that has
- ** already been dequoted.
- */
- static Expr sqlite3Expr(
- sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */
- int op, /* Expression opcode */
- string zToken /* Token argument. Might be NULL */
- )
- {
- Token x = new Token();
- x.z = zToken;
- x.n = !string.IsNullOrEmpty( zToken ) ? sqlite3Strlen30( zToken ) : 0;
- return sqlite3ExprAlloc( db, op, x, 0 );
- }
-
- /*
- ** Attach subtrees pLeft and pRight to the Expr node pRoot.
- **
- ** If pRoot==NULL that means that a memory allocation error has occurred.
- ** In that case, delete the subtrees pLeft and pRight.
- */
- static void sqlite3ExprAttachSubtrees(
- sqlite3 db,
- Expr pRoot,
- Expr pLeft,
- Expr pRight
- )
- {
- if ( pRoot == null )
- {
- //Debug.Assert( db.mallocFailed != 0 );
- sqlite3ExprDelete( db, ref pLeft );
- sqlite3ExprDelete( db, ref pRight );
- }
- else
- {
- if ( pRight != null )
- {
- pRoot.pRight = pRight;
- if ( ( pRight.flags & EP_ExpCollate ) != 0 )
- {
- pRoot.flags |= EP_ExpCollate;
- pRoot.pColl = pRight.pColl;
- }
+ }
+ return pNew;
}
- if ( pLeft != null )
- {
- pRoot.pLeft = pLeft;
- if ( ( pLeft.flags & EP_ExpCollate ) != 0 )
- {
- pRoot.flags |= EP_ExpCollate;
- pRoot.pColl = pLeft.pColl;
- }
+
+ /*
+ ** Allocate a new expression node from a zero-terminated token that has
+ ** already been dequoted.
+ */
+ static Expr sqlite3Expr(
+ sqlite3 db, /* Handle for sqlite3DbMallocZero() (may be null) */
+ int op, /* Expression opcode */
+ string zToken /* Token argument. Might be NULL */
+ ) {
+ Token x = new Token();
+ x.z = zToken;
+ x.n = !string.IsNullOrEmpty(zToken) ? sqlite3Strlen30(zToken) : 0;
+ return sqlite3ExprAlloc(db, op, x, 0);
}
- exprSetHeight( pRoot );
- }
- }
- /*
- ** Allocate a Expr node which joins as many as two subtrees.
- **
- ** One or both of the subtrees can be NULL. Return a pointer to the new
- ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
- ** free the subtrees and return NULL.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static Expr sqlite3PExpr( Parse pParse, int op, int null_3, int null_4, int null_5 )
- {
- return sqlite3PExpr( pParse, op, null, null, null );
- }
- static Expr sqlite3PExpr( Parse pParse, int op, int null_3, int null_4, Token pToken )
- {
- return sqlite3PExpr( pParse, op, null, null, pToken );
- }
- static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, int null_4, int null_5 )
- {
- return sqlite3PExpr( pParse, op, pLeft, null, null );
- }
- static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, int null_4, Token pToken )
- {
- return sqlite3PExpr( pParse, op, pLeft, null, pToken );
- }
- static Expr sqlite3PExpr( Parse pParse, int op, Expr pLeft, Expr pRight, int null_5 )
- {
- return sqlite3PExpr( pParse, op, pLeft, pRight, null );
- }
- static Expr sqlite3PExpr(
- Parse pParse, /* Parsing context */
- int op, /* Expression opcode */
- Expr pLeft, /* Left operand */
- Expr pRight, /* Right operand */
- Token pToken /* Argument Token */
- )
- {
- Expr p = sqlite3ExprAlloc( pParse.db, op, pToken, 1 );
- sqlite3ExprAttachSubtrees( pParse.db, p, pLeft, pRight );
- if ( p != null )
- {
- sqlite3ExprCheckHeight( pParse, p.nHeight );
- }
- return p;
- }
+ /*
+ ** Attach subtrees pLeft and pRight to the Expr node pRoot.
+ **
+ ** If pRoot==NULL that means that a memory allocation error has occurred.
+ ** In that case, delete the subtrees pLeft and pRight.
+ */
+ static void sqlite3ExprAttachSubtrees(
+ sqlite3 db,
+ Expr pRoot,
+ Expr pLeft,
+ Expr pRight
+ ) {
+ if (pRoot == null) {
+ //Debug.Assert( db.mallocFailed != 0 );
+ sqlite3ExprDelete(db, ref pLeft);
+ sqlite3ExprDelete(db, ref pRight);
+ } else {
+ if (pRight != null) {
+ pRoot.pRight = pRight;
+ if ((pRight.flags & EP_ExpCollate) != 0) {
+ pRoot.flags |= EP_ExpCollate;
+ pRoot.pColl = pRight.pColl;
+ }
+ }
+ if (pLeft != null) {
+ pRoot.pLeft = pLeft;
+ if ((pLeft.flags & EP_ExpCollate) != 0) {
+ pRoot.flags |= EP_ExpCollate;
+ pRoot.pColl = pLeft.pColl;
+ }
+ }
+ exprSetHeight(pRoot);
+ }
+ }
- /*
- ** Join two expressions using an AND operator. If either expression is
- ** NULL, then just return the other expression.
- */
- static Expr sqlite3ExprAnd( sqlite3 db, Expr pLeft, Expr pRight )
- {
- if ( pLeft == null )
- {
- return pRight;
- }
- else if ( pRight == null )
- {
- return pLeft;
- }
- else
- {
- Expr pNew = sqlite3ExprAlloc( db, TK_AND, null, 0 );
- sqlite3ExprAttachSubtrees( db, pNew, pLeft, pRight );
- return pNew;
- }
- }
+ /*
+ ** Allocate a Expr node which joins as many as two subtrees.
+ **
+ ** One or both of the subtrees can be NULL. Return a pointer to the new
+ ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
+ ** free the subtrees and return NULL.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static Expr sqlite3PExpr(Parse pParse, int op, int null_3, int null_4, int null_5) {
+ return sqlite3PExpr(pParse, op, null, null, null);
+ }
+ static Expr sqlite3PExpr(Parse pParse, int op, int null_3, int null_4, Token pToken) {
+ return sqlite3PExpr(pParse, op, null, null, pToken);
+ }
+ static Expr sqlite3PExpr(Parse pParse, int op, Expr pLeft, int null_4, int null_5) {
+ return sqlite3PExpr(pParse, op, pLeft, null, null);
+ }
+ static Expr sqlite3PExpr(Parse pParse, int op, Expr pLeft, int null_4, Token pToken) {
+ return sqlite3PExpr(pParse, op, pLeft, null, pToken);
+ }
+ static Expr sqlite3PExpr(Parse pParse, int op, Expr pLeft, Expr pRight, int null_5) {
+ return sqlite3PExpr(pParse, op, pLeft, pRight, null);
+ }
+ static Expr sqlite3PExpr(
+ Parse pParse, /* Parsing context */
+ int op, /* Expression opcode */
+ Expr pLeft, /* Left operand */
+ Expr pRight, /* Right operand */
+ Token pToken /* Argument Token */
+ ) {
+ Expr p = sqlite3ExprAlloc(pParse.db, op, pToken, 1);
+ sqlite3ExprAttachSubtrees(pParse.db, p, pLeft, pRight);
+ if (p != null) {
+ sqlite3ExprCheckHeight(pParse, p.nHeight);
+ }
+ return p;
+ }
- /*
- ** Construct a new expression node for a function with multiple
- ** arguments.
- */
- // OVERLOADS, so I don't need to rewrite parse.c
- static Expr sqlite3ExprFunction( Parse pParse, int null_2, Token pToken )
- {
- return sqlite3ExprFunction( pParse, null, pToken );
- }
- static Expr sqlite3ExprFunction( Parse pParse, ExprList pList, int null_3 )
- {
- return sqlite3ExprFunction( pParse, pList, null );
- }
- static Expr sqlite3ExprFunction( Parse pParse, ExprList pList, Token pToken )
- {
- Expr pNew;
- sqlite3 db = pParse.db;
- Debug.Assert( pToken != null );
- pNew = sqlite3ExprAlloc( db, TK_FUNCTION, pToken, 1 );
- if ( pNew == null )
- {
- sqlite3ExprListDelete( db, ref pList ); /* Avoid memory leak when malloc fails */
- return null;
- }
- pNew.x.pList = pList;
- Debug.Assert( !ExprHasProperty( pNew, EP_xIsSelect ) );
-
- sqlite3ExprSetHeight( pParse, pNew );
- return pNew;
- }
+ /*
+ ** Join two expressions using an AND operator. If either expression is
+ ** NULL, then just return the other expression.
+ */
+ static Expr sqlite3ExprAnd(sqlite3 db, Expr pLeft, Expr pRight) {
+ if (pLeft == null) {
+ return pRight;
+ } else if (pRight == null) {
+ return pLeft;
+ } else {
+ Expr pNew = sqlite3ExprAlloc(db, TK_AND, null, 0);
+ sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
+ return pNew;
+ }
+ }
- /*
- ** Assign a variable number to an expression that encodes a wildcard
- ** in the original SQL statement.
- **
- ** Wildcards consisting of a single "?" are assigned the next sequential
- ** variable number.
- **
- ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
- ** sure "nnn" is not too be to avoid a denial of service attack when
- ** the SQL statement comes from an external source.
- **
- ** Wildcards of the form ":aaa", "@aaa" or "$aaa" are assigned the same number
- ** as the previous instance of the same wildcard. Or if this is the first
- ** instance of the wildcard, the next sequenial variable number is
- ** assigned.
- */
- static void sqlite3ExprAssignVarNumber( Parse pParse, Expr pExpr )
- {
- sqlite3 db = pParse.db;
- string z;
-
- if ( pExpr == null )
- return;
- Debug.Assert( !ExprHasAnyProperty( pExpr, EP_IntValue | EP_Reduced | EP_TokenOnly ) );
- z = pExpr.u.zToken;
- Debug.Assert( z != null );
- Debug.Assert( z.Length != 0 );
- if ( z.Length == 1 )
- {
- /* Wildcard of the form "?". Assign the next variable number */
- Debug.Assert( z[0] == '?' );
- pExpr.iColumn = (ynVar)( ++pParse.nVar );
- }else{
- ynVar x = 0;
- int n = sqlite3Strlen30(z);
- if( z[0]=='?' ){
- /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
- ** use it as the variable number */
- i64 i = 0;
- bool bOk = 0 == sqlite3Atoi64( z.Substring( 1 ), ref i, n - 1, SQLITE_UTF8 );
- pExpr.iColumn = x=(ynVar)i;
- testcase( i == 0 );
- testcase( i == 1 );
- testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] - 1 );
- testcase( i == db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
- if ( bOk == false || i < 1 || i > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] )
- {
- sqlite3ErrorMsg( pParse, "variable number must be between ?1 and ?%d",
- db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
- x=0;
+ /*
+ ** Construct a new expression node for a function with multiple
+ ** arguments.
+ */
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static Expr sqlite3ExprFunction(Parse pParse, int null_2, Token pToken) {
+ return sqlite3ExprFunction(pParse, null, pToken);
}
- if ( i > pParse.nVar )
- {
- pParse.nVar = (int)i;
+ static Expr sqlite3ExprFunction(Parse pParse, ExprList pList, int null_3) {
+ return sqlite3ExprFunction(pParse, pList, null);
+ }
+ static Expr sqlite3ExprFunction(Parse pParse, ExprList pList, Token pToken) {
+ Expr pNew;
+ sqlite3 db = pParse.db;
+ Debug.Assert(pToken != null);
+ pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
+ if (pNew == null) {
+ sqlite3ExprListDelete(db, ref pList); /* Avoid memory leak when malloc fails */
+ return null;
+ }
+ pNew.x.pList = pList;
+ Debug.Assert(!ExprHasProperty(pNew, EP_xIsSelect));
+
+ sqlite3ExprSetHeight(pParse, pNew);
+ return pNew;
}
- }
- else
- {
- /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
- ** number as the prior appearance of the same name, or if the name
- ** has never appeared before, reuse the same variable number
+
+ /*
+ ** Assign a variable number to an expression that encodes a wildcard
+ ** in the original SQL statement.
+ **
+ ** Wildcards consisting of a single "?" are assigned the next sequential
+ ** variable number.
+ **
+ ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
+ ** sure "nnn" is not too be to avoid a denial of service attack when
+ ** the SQL statement comes from an external source.
+ **
+ ** Wildcards of the form ":aaa", "@aaa" or "$aaa" are assigned the same number
+ ** as the previous instance of the same wildcard. Or if this is the first
+ ** instance of the wildcard, the next sequenial variable number is
+ ** assigned.
*/
- ynVar i;
- for(i=0; i db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]) {
+ sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
+ db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
+ x = 0;
+ }
+ if (i > pParse.nVar) {
+ pParse.nVar = (int)i;
+ }
+ } else {
+ /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
+ ** number as the prior appearance of the same name, or if the name
+ ** has never appeared before, reuse the same variable number
+ */
+ ynVar i;
+ for (i = 0; i < pParse.nzVar; i++) {
+ if (pParse.azVar[i] != null && string.Equals(z, pParse.azVar[i], StringComparison.Ordinal)) //memcmp(pParse.azVar[i],z,n+1)==0 )
+ {
+ pExpr.iColumn = x = (ynVar)(i + 1);
+ break;
+ }
+ }
+ if (x == 0) x = pExpr.iColumn = (ynVar)(++pParse.nVar);
+ }
+ if (x > 0) {
+ if (x > pParse.nzVar) {
+ //char **a;
+ //a = sqlite3DbRealloc(db, pParse.azVar, x*sizeof(a[0]));
+ //if( a==0 ) return; /* Error reported through db.mallocFailed */
+ //pParse.azVar = a;
+ //memset(&a[pParse.nzVar], 0, (x-pParse.nzVar)*sizeof(a[0]));
+ Array.Resize(ref pParse.azVar, x);
+ pParse.nzVar = x;
+ }
+ if (z[0] != '?' || pParse.azVar[x - 1] == null) {
+ //sqlite3DbFree(db, pParse.azVar[x-1]);
+ pParse.azVar[x - 1] = z.Substring(0, n);//sqlite3DbStrNDup( db, z, n );
+ }
+ }
+ }
+ if (pParse.nErr == 0 && pParse.nVar > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]) {
+ sqlite3ErrorMsg(pParse, "too many SQL variables");
+ }
}
- }
- if( x==0 ) x = pExpr.iColumn = (ynVar)(++pParse.nVar);
- }
- if( x>0 ){
- if( x>pParse.nzVar ){
- //char **a;
- //a = sqlite3DbRealloc(db, pParse.azVar, x*sizeof(a[0]));
- //if( a==0 ) return; /* Error reported through db.mallocFailed */
- //pParse.azVar = a;
- //memset(&a[pParse.nzVar], 0, (x-pParse.nzVar)*sizeof(a[0]));
- Array.Resize( ref pParse.azVar, x );
- pParse.nzVar = x;
- }
- if( z[0]!='?' || pParse.azVar[x-1]==null )
- {
- //sqlite3DbFree(db, pParse.azVar[x-1]);
- pParse.azVar[x - 1] = z.Substring( 0, n );//sqlite3DbStrNDup( db, z, n );
- }
- }
- }
- if ( pParse.nErr == 0 && pParse.nVar > db.aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] )
- {
- sqlite3ErrorMsg( pParse, "too many SQL variables" );
- }
- }
- /*
- ** Recursively delete an expression tree.
- */
- static void sqlite3ExprDelete( sqlite3 db, ref Expr p )
- {
- if ( p == null )
- return;
- /* Sanity check: Assert that the IntValue is non-negative if it exists */
- Debug.Assert( !ExprHasProperty( p, EP_IntValue ) || p.u.iValue >= 0 );
- if ( !ExprHasAnyProperty( p, EP_TokenOnly ) )
- {
- sqlite3ExprDelete( db, ref p.pLeft );
- sqlite3ExprDelete( db, ref p.pRight );
- if ( !ExprHasProperty( p, EP_Reduced ) && ( p.flags2 & EP2_MallocedToken ) != 0 )
- {
+ /*
+ ** Recursively delete an expression tree.
+ */
+ static void sqlite3ExprDelete(sqlite3 db, ref Expr p) {
+ if (p == null)
+ return;
+ /* Sanity check: Assert that the IntValue is non-negative if it exists */
+ Debug.Assert(!ExprHasProperty(p, EP_IntValue) || p.u.iValue >= 0);
+ if (!ExprHasAnyProperty(p, EP_TokenOnly)) {
+ sqlite3ExprDelete(db, ref p.pLeft);
+ sqlite3ExprDelete(db, ref p.pRight);
+ if (!ExprHasProperty(p, EP_Reduced) && (p.flags2 & EP2_MallocedToken) != 0) {
#if DEBUG_CLASS_EXPR || DEBUG_CLASS_ALL
sqlite3DbFree( db, ref p.u._zToken );
#else
- sqlite3DbFree( db, ref p.u.zToken );
+ sqlite3DbFree(db, ref p.u.zToken);
#endif
+ }
+ if (ExprHasProperty(p, EP_xIsSelect)) {
+ sqlite3SelectDelete(db, ref p.x.pSelect);
+ } else {
+ sqlite3ExprListDelete(db, ref p.x.pList);
+ }
+ }
+ if (!ExprHasProperty(p, EP_Static)) {
+ sqlite3DbFree(db, ref p);
+ }
}
- if ( ExprHasProperty( p, EP_xIsSelect ) )
- {
- sqlite3SelectDelete( db, ref p.x.pSelect );
- }
- else
- {
- sqlite3ExprListDelete( db, ref p.x.pList );
- }
- }
- if ( !ExprHasProperty( p, EP_Static ) )
- {
- sqlite3DbFree( db, ref p );
- }
- }
-
- /*
- ** Return the number of bytes allocated for the expression structure
- ** passed as the first argument. This is always one of EXPR_FULLSIZE,
- ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
- */
- static int exprStructSize( Expr p )
- {
- if ( ExprHasProperty( p, EP_TokenOnly ) )
- return EXPR_TOKENONLYSIZE;
- if ( ExprHasProperty( p, EP_Reduced ) )
- return EXPR_REDUCEDSIZE;
- return EXPR_FULLSIZE;
- }
- /*
- ** The dupedExpr*Size() routines each return the number of bytes required
- ** to store a copy of an expression or expression tree. They differ in
- ** how much of the tree is measured.
- **
- ** dupedExprStructSize() Size of only the Expr structure
- ** dupedExprNodeSize() Size of Expr + space for token
- ** dupedExprSize() Expr + token + subtree components
- **
- ***************************************************************************
- **
- ** The dupedExprStructSize() function returns two values OR-ed together:
- ** (1) the space required for a copy of the Expr structure only and
- ** (2) the EP_xxx flags that indicate what the structure size should be.
- ** The return values is always one of:
- **
- ** EXPR_FULLSIZE
- ** EXPR_REDUCEDSIZE | EP_Reduced
- ** EXPR_TOKENONLYSIZE | EP_TokenOnly
- **
- ** The size of the structure can be found by masking the return value
- ** of this routine with 0xfff. The flags can be found by masking the
- ** return value with EP_Reduced|EP_TokenOnly.
- **
- ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
- ** (unreduced) Expr objects as they or originally constructed by the parser.
- ** During expression analysis, extra information is computed and moved into
- ** later parts of teh Expr object and that extra information might get chopped
- ** off if the expression is reduced. Note also that it does not work to
- ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
- ** to reduce a pristine expression tree from the parser. The implementation
- ** of dupedExprStructSize() contain multiple Debug.Assert() statements that attempt
- ** to enforce this constraint.
- */
- static int dupedExprStructSize( Expr p, int flags )
- {
- int nSize;
- Debug.Assert( flags == EXPRDUP_REDUCE || flags == 0 ); /* Only one flag value allowed */
- if ( 0 == ( flags & EXPRDUP_REDUCE ) )
- {
- nSize = EXPR_FULLSIZE;
- }
- else
- {
- Debug.Assert( !ExprHasAnyProperty( p, EP_TokenOnly | EP_Reduced ) );
- Debug.Assert( !ExprHasProperty( p, EP_FromJoin ) );
- Debug.Assert( ( p.flags2 & EP2_MallocedToken ) == 0 );
- Debug.Assert( ( p.flags2 & EP2_Irreducible ) == 0 );
- if ( p.pLeft != null || p.pRight != null || p.pColl != null || p.x.pList != null || p.x.pSelect != null )
- {
- nSize = EXPR_REDUCEDSIZE | EP_Reduced;
- }
- else
- {
- nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
+ /*
+ ** Return the number of bytes allocated for the expression structure
+ ** passed as the first argument. This is always one of EXPR_FULLSIZE,
+ ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
+ */
+ static int exprStructSize(Expr p) {
+ if (ExprHasProperty(p, EP_TokenOnly))
+ return EXPR_TOKENONLYSIZE;
+ if (ExprHasProperty(p, EP_Reduced))
+ return EXPR_REDUCEDSIZE;
+ return EXPR_FULLSIZE;
}
- }
- return nSize;
- }
-
- /*
- ** This function returns the space in bytes required to store the copy
- ** of the Expr structure and a copy of the Expr.u.zToken string (if that
- ** string is defined.)
- */
- static int dupedExprNodeSize( Expr p, int flags )
- {
- int nByte = dupedExprStructSize( p, flags ) & 0xfff;
- if ( !ExprHasProperty( p, EP_IntValue ) && p.u.zToken != null )
- {
- nByte += sqlite3Strlen30( p.u.zToken ) + 1;
- }
- return ROUND8( nByte );
- }
- /*
- ** Return the number of bytes required to create a duplicate of the
- ** expression passed as the first argument. The second argument is a
- ** mask containing EXPRDUP_XXX flags.
- **
- ** The value returned includes space to create a copy of the Expr struct
- ** itself and the buffer referred to by Expr.u.zToken, if any.
- **
- ** If the EXPRDUP_REDUCE flag is set, then the return value includes
- ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
- ** and Expr.pRight variables (but not for any structures pointed to or
- ** descended from the Expr.x.pList or Expr.x.pSelect variables).
- */
- static int dupedExprSize( Expr p, int flags )
- {
- int nByte = 0;
- if ( p != null )
- {
- nByte = dupedExprNodeSize( p, flags );
- if ( ( flags & EXPRDUP_REDUCE ) != 0 )
- {
- nByte += dupedExprSize( p.pLeft, flags ) + dupedExprSize( p.pRight, flags );
+ /*
+ ** The dupedExpr*Size() routines each return the number of bytes required
+ ** to store a copy of an expression or expression tree. They differ in
+ ** how much of the tree is measured.
+ **
+ ** dupedExprStructSize() Size of only the Expr structure
+ ** dupedExprNodeSize() Size of Expr + space for token
+ ** dupedExprSize() Expr + token + subtree components
+ **
+ ***************************************************************************
+ **
+ ** The dupedExprStructSize() function returns two values OR-ed together:
+ ** (1) the space required for a copy of the Expr structure only and
+ ** (2) the EP_xxx flags that indicate what the structure size should be.
+ ** The return values is always one of:
+ **
+ ** EXPR_FULLSIZE
+ ** EXPR_REDUCEDSIZE | EP_Reduced
+ ** EXPR_TOKENONLYSIZE | EP_TokenOnly
+ **
+ ** The size of the structure can be found by masking the return value
+ ** of this routine with 0xfff. The flags can be found by masking the
+ ** return value with EP_Reduced|EP_TokenOnly.
+ **
+ ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
+ ** (unreduced) Expr objects as they or originally constructed by the parser.
+ ** During expression analysis, extra information is computed and moved into
+ ** later parts of teh Expr object and that extra information might get chopped
+ ** off if the expression is reduced. Note also that it does not work to
+ ** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
+ ** to reduce a pristine expression tree from the parser. The implementation
+ ** of dupedExprStructSize() contain multiple Debug.Assert() statements that attempt
+ ** to enforce this constraint.
+ */
+ static int dupedExprStructSize(Expr p, int flags) {
+ int nSize;
+ Debug.Assert(flags == EXPRDUP_REDUCE || flags == 0); /* Only one flag value allowed */
+ if (0 == (flags & EXPRDUP_REDUCE)) {
+ nSize = EXPR_FULLSIZE;
+ } else {
+ Debug.Assert(!ExprHasAnyProperty(p, EP_TokenOnly | EP_Reduced));
+ Debug.Assert(!ExprHasProperty(p, EP_FromJoin));
+ Debug.Assert((p.flags2 & EP2_MallocedToken) == 0);
+ Debug.Assert((p.flags2 & EP2_Irreducible) == 0);
+ if (p.pLeft != null || p.pRight != null || p.pColl != null || p.x.pList != null || p.x.pSelect != null) {
+ nSize = EXPR_REDUCEDSIZE | EP_Reduced;
+ } else {
+ nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
+ }
+ }
+ return nSize;
}
- }
- return nByte;
- }
- /*
- ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
- ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
- ** to store the copy of expression p, the copies of p->u.zToken
- ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
- ** if any. Before returning, *pzBuffer is set to the first byte passed the
- ** portion of the buffer copied into by this function.
- */
- static Expr exprDup( sqlite3 db, Expr p, int flags, ref Expr pzBuffer )
- {
- Expr pNew = null; /* Value to return */
- if ( p != null )
- {
- bool isReduced = ( flags & EXPRDUP_REDUCE ) != 0;
- ////Expr zAlloc = new Expr();
- u32 staticFlag = 0;
-
- Debug.Assert( pzBuffer == null || isReduced );
-
- /* Figure out where to write the new Expr structure. */
- //if ( pzBuffer !=null)
- //{
- // zAlloc = pzBuffer;
- // staticFlag = EP_Static;
- //}
- //else
- //{
- ///Expr zAlloc = new Expr();//sqlite3DbMallocRaw( db, dupedExprSize( p, flags ) );
- //}
- // (Expr)zAlloc;
-
- //if ( pNew != null )
- {
- /* Set nNewSize to the size allocated for the structure pointed to
- ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
- ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
- ** by the copy of the p->u.zToken string (if any).
- */
- int nStructSize = dupedExprStructSize( p, flags );
- ////int nNewSize = nStructSize & 0xfff;
- ////int nToken;
- ////if ( !ExprHasProperty( p, EP_IntValue ) && !string.IsNullOrEmpty( p.u.zToken ) )
- ////{
- //// nToken = sqlite3Strlen30( p.u.zToken );
- ////}
- ////else
- ////{
- //// nToken = 0;
- ////}
- if ( isReduced )
- {
- Debug.Assert( !ExprHasProperty( p, EP_Reduced ) );
- pNew = p.Copy( EXPR_TOKENONLYSIZE );////memcpy( zAlloc, p, nNewSize );
- }
- else
- {
- ////int nSize = exprStructSize( p );
- ////memcpy( zAlloc, p, nSize );
- pNew = p.Copy();
- ////memset( &zAlloc[nSize], 0, EXPR_FULLSIZE - nSize );
- }
+ /*
+ ** This function returns the space in bytes required to store the copy
+ ** of the Expr structure and a copy of the Expr.u.zToken string (if that
+ ** string is defined.)
+ */
+ static int dupedExprNodeSize(Expr p, int flags) {
+ int nByte = dupedExprStructSize(p, flags) & 0xfff;
+ if (!ExprHasProperty(p, EP_IntValue) && p.u.zToken != null) {
+ nByte += sqlite3Strlen30(p.u.zToken) + 1;
+ }
+ return ROUND8(nByte);
+ }
- /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
- unchecked
- {
- pNew.flags &= (ushort)( ~( EP_Reduced | EP_TokenOnly | EP_Static ) );
- }
- pNew.flags |= (ushort)( nStructSize & ( EP_Reduced | EP_TokenOnly ) );
- pNew.flags |= (ushort)staticFlag;
+ /*
+ ** Return the number of bytes required to create a duplicate of the
+ ** expression passed as the first argument. The second argument is a
+ ** mask containing EXPRDUP_XXX flags.
+ **
+ ** The value returned includes space to create a copy of the Expr struct
+ ** itself and the buffer referred to by Expr.u.zToken, if any.
+ **
+ ** If the EXPRDUP_REDUCE flag is set, then the return value includes
+ ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
+ ** and Expr.pRight variables (but not for any structures pointed to or
+ ** descended from the Expr.x.pList or Expr.x.pSelect variables).
+ */
+ static int dupedExprSize(Expr p, int flags) {
+ int nByte = 0;
+ if (p != null) {
+ nByte = dupedExprNodeSize(p, flags);
+ if ((flags & EXPRDUP_REDUCE) != 0) {
+ nByte += dupedExprSize(p.pLeft, flags) + dupedExprSize(p.pRight, flags);
+ }
+ }
+ return nByte;
+ }
- /* Copy the p->u.zToken string, if any. */
- ////if ( nToken != 0 )
- ////{
- //// string zToken;// = pNew.u.zToken = (char)&zAlloc[nNewSize];
- //// zToken = p.u.zToken.Substring( 0, nToken );// memcpy( zToken, p.u.zToken, nToken );
- ////}
+ /*
+ ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
+ ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
+ ** to store the copy of expression p, the copies of p->u.zToken
+ ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
+ ** if any. Before returning, *pzBuffer is set to the first byte passed the
+ ** portion of the buffer copied into by this function.
+ */
+ static Expr exprDup(sqlite3 db, Expr p, int flags, ref Expr pzBuffer) {
+ Expr pNew = null; /* Value to return */
+ if (p != null) {
+ bool isReduced = (flags & EXPRDUP_REDUCE) != 0;
+ ////Expr zAlloc = new Expr();
+ u32 staticFlag = 0;
+
+ Debug.Assert(pzBuffer == null || isReduced);
+
+ /* Figure out where to write the new Expr structure. */
+ //if ( pzBuffer !=null)
+ //{
+ // zAlloc = pzBuffer;
+ // staticFlag = EP_Static;
+ //}
+ //else
+ //{
+ ///Expr zAlloc = new Expr();//sqlite3DbMallocRaw( db, dupedExprSize( p, flags ) );
+ //}
+ // (Expr)zAlloc;
+
+ //if ( pNew != null )
+ {
+ /* Set nNewSize to the size allocated for the structure pointed to
+ ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
+ ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
+ ** by the copy of the p->u.zToken string (if any).
+ */
+ int nStructSize = dupedExprStructSize(p, flags);
+ ////int nNewSize = nStructSize & 0xfff;
+ ////int nToken;
+ ////if ( !ExprHasProperty( p, EP_IntValue ) && !string.IsNullOrEmpty( p.u.zToken ) )
+ ////{
+ //// nToken = sqlite3Strlen30( p.u.zToken );
+ ////}
+ ////else
+ ////{
+ //// nToken = 0;
+ ////}
+ if (isReduced) {
+ Debug.Assert(!ExprHasProperty(p, EP_Reduced));
+ pNew = p.Copy(EXPR_TOKENONLYSIZE);////memcpy( zAlloc, p, nNewSize );
+ } else {
+ ////int nSize = exprStructSize( p );
+ ////memcpy( zAlloc, p, nSize );
+ pNew = p.Copy();
+ ////memset( &zAlloc[nSize], 0, EXPR_FULLSIZE - nSize );
+ }
- if ( 0 == ( ( p.flags | pNew.flags ) & EP_TokenOnly ) )
- {
- /* Fill in the pNew.x.pSelect or pNew.x.pList member. */
- if ( ExprHasProperty( p, EP_xIsSelect ) )
- {
- pNew.x.pSelect = sqlite3SelectDup( db, p.x.pSelect, isReduced ? 1 : 0 );
- }
- else
- {
- pNew.x.pList = sqlite3ExprListDup( db, p.x.pList, isReduced ? 1 : 0 );
- }
- }
+ /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
+ unchecked {
+ pNew.flags &= (ushort)(~(EP_Reduced | EP_TokenOnly | EP_Static));
+ }
+ pNew.flags |= (ushort)(nStructSize & (EP_Reduced | EP_TokenOnly));
+ pNew.flags |= (ushort)staticFlag;
+
+ /* Copy the p->u.zToken string, if any. */
+ ////if ( nToken != 0 )
+ ////{
+ //// string zToken;// = pNew.u.zToken = (char)&zAlloc[nNewSize];
+ //// zToken = p.u.zToken.Substring( 0, nToken );// memcpy( zToken, p.u.zToken, nToken );
+ ////}
+
+ if (0 == ((p.flags | pNew.flags) & EP_TokenOnly)) {
+ /* Fill in the pNew.x.pSelect or pNew.x.pList member. */
+ if (ExprHasProperty(p, EP_xIsSelect)) {
+ pNew.x.pSelect = sqlite3SelectDup(db, p.x.pSelect, isReduced ? 1 : 0);
+ } else {
+ pNew.x.pList = sqlite3ExprListDup(db, p.x.pList, isReduced ? 1 : 0);
+ }
+ }
- /* Fill in pNew.pLeft and pNew.pRight. */
- if ( ExprHasAnyProperty( pNew, EP_Reduced | EP_TokenOnly ) )
- {
- //zAlloc += dupedExprNodeSize( p, flags );
- if ( ExprHasProperty( pNew, EP_Reduced ) )
- {
- pNew.pLeft = exprDup( db, p.pLeft, EXPRDUP_REDUCE, ref pzBuffer );
- pNew.pRight = exprDup( db, p.pRight, EXPRDUP_REDUCE, ref pzBuffer );
- }
- //if ( pzBuffer != null )
- //{
- // pzBuffer = zAlloc;
- //}
- }
- else
- {
- pNew.flags2 = 0;
- if ( !ExprHasAnyProperty( p, EP_TokenOnly ) )
- {
- pNew.pLeft = sqlite3ExprDup( db, p.pLeft, 0 );
- pNew.pRight = sqlite3ExprDup( db, p.pRight, 0 );
+ /* Fill in pNew.pLeft and pNew.pRight. */
+ if (ExprHasAnyProperty(pNew, EP_Reduced | EP_TokenOnly)) {
+ //zAlloc += dupedExprNodeSize( p, flags );
+ if (ExprHasProperty(pNew, EP_Reduced)) {
+ pNew.pLeft = exprDup(db, p.pLeft, EXPRDUP_REDUCE, ref pzBuffer);
+ pNew.pRight = exprDup(db, p.pRight, EXPRDUP_REDUCE, ref pzBuffer);
+ }
+ //if ( pzBuffer != null )
+ //{
+ // pzBuffer = zAlloc;
+ //}
+ } else {
+ pNew.flags2 = 0;
+ if (!ExprHasAnyProperty(p, EP_TokenOnly)) {
+ pNew.pLeft = sqlite3ExprDup(db, p.pLeft, 0);
+ pNew.pRight = sqlite3ExprDup(db, p.pRight, 0);
+ }
+ }
+ }
}
- }
+ return pNew;
}
- }
- return pNew;
- }
- /*
- ** The following group of routines make deep copies of expressions,
- ** expression lists, ID lists, and select statements. The copies can
- ** be deleted (by being passed to their respective ...Delete() routines)
- ** without effecting the originals.
- **
- ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
- ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
- ** by subsequent calls to sqlite*ListAppend() routines.
- **
- ** Any tables that the SrcList might point to are not duplicated.
- **
- ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
- ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
- ** truncated version of the usual Expr structure that will be stored as
- ** part of the in-memory representation of the database schema.
- */
- static Expr sqlite3ExprDup( sqlite3 db, Expr p, int flags )
- {
- Expr ExprDummy = null;
- return exprDup( db, p, flags, ref ExprDummy );
- }
+ /*
+ ** The following group of routines make deep copies of expressions,
+ ** expression lists, ID lists, and select statements. The copies can
+ ** be deleted (by being passed to their respective ...Delete() routines)
+ ** without effecting the originals.
+ **
+ ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
+ ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
+ ** by subsequent calls to sqlite*ListAppend() routines.
+ **
+ ** Any tables that the SrcList might point to are not duplicated.
+ **
+ ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
+ ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
+ ** truncated version of the usual Expr structure that will be stored as
+ ** part of the in-memory representation of the database schema.
+ */
+ static Expr sqlite3ExprDup(sqlite3 db, Expr p, int flags) {
+ Expr ExprDummy = null;
+ return exprDup(db, p, flags, ref ExprDummy);
+ }
- static ExprList sqlite3ExprListDup( sqlite3 db, ExprList p, int flags )
- {
- ExprList pNew;
- ExprList_item pItem;
- ExprList_item pOldItem;
-
- if ( p == null )
- return null;
- pNew = new ExprList();//sqlite3DbMallocRaw(db, sizeof(*pNew) );
- //if ( pNew == null ) return null;
- pNew.iECursor = 0;
- pNew.nExpr = pNew.nAlloc = p.nExpr;
- pNew.a = new ExprList_item[p.nExpr];//sqlite3DbMallocRaw(db, p.nExpr*sizeof(p.a[0]) );
- //if( pItem==null ){
- // sqlite3DbFree(db,ref pNew);
- // return null;
- //}
- //pOldItem = p.a;
- for (int i = 0; i < p.nExpr; i++ )
- {//pItem++, pOldItem++){
- pItem = pNew.a[i] = new ExprList_item();
- pOldItem = p.a[i];
- Expr pOldExpr = pOldItem.pExpr;
- pItem.pExpr = sqlite3ExprDup( db, pOldExpr, flags );
- pItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName);
- pItem.zSpan = pOldItem.zSpan;// sqlite3DbStrDup( db, pOldItem.zSpan );
- pItem.sortOrder = pOldItem.sortOrder;
- pItem.done = 0;
- pItem.iCol = pOldItem.iCol;
- pItem.iAlias = pOldItem.iAlias;
- }
- return pNew;
- }
+ static ExprList sqlite3ExprListDup(sqlite3 db, ExprList p, int flags) {
+ ExprList pNew;
+ ExprList_item pItem;
+ ExprList_item pOldItem;
+
+ if (p == null)
+ return null;
+ pNew = new ExprList();//sqlite3DbMallocRaw(db, sizeof(*pNew) );
+ //if ( pNew == null ) return null;
+ pNew.iECursor = 0;
+ pNew.nExpr = pNew.nAlloc = p.nExpr;
+ pNew.a = new ExprList_item[p.nExpr];//sqlite3DbMallocRaw(db, p.nExpr*sizeof(p.a[0]) );
+ //if( pItem==null ){
+ // sqlite3DbFree(db,ref pNew);
+ // return null;
+ //}
+ //pOldItem = p.a;
+ for (int i = 0; i < p.nExpr; i++) {//pItem++, pOldItem++){
+ pItem = pNew.a[i] = new ExprList_item();
+ pOldItem = p.a[i];
+ Expr pOldExpr = pOldItem.pExpr;
+ pItem.pExpr = sqlite3ExprDup(db, pOldExpr, flags);
+ pItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName);
+ pItem.zSpan = pOldItem.zSpan;// sqlite3DbStrDup( db, pOldItem.zSpan );
+ pItem.sortOrder = pOldItem.sortOrder;
+ pItem.done = 0;
+ pItem.iCol = pOldItem.iCol;
+ pItem.iAlias = pOldItem.iAlias;
+ }
+ return pNew;
+ }
- /*
- ** If cursors, triggers, views and subqueries are all omitted from
- ** the build, then none of the following routines, except for
- ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
- ** called with a NULL argument.
- */
-#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER || !SQLITE_OMIT_SUBQUERY
- static SrcList sqlite3SrcListDup( sqlite3 db, SrcList p, int flags )
- {
- SrcList pNew;
- int nByte;
- if ( p == null )
- return null;
- //nByte = sizeof(*p) + (p.nSrc>0 ? sizeof(p.a[0]) * (p.nSrc-1) : 0);
- pNew = new SrcList();//sqlite3DbMallocRaw(db, nByte );
- if ( p.nSrc > 0 )
- pNew.a = new SrcList_item[p.nSrc];
- if ( pNew == null )
- return null;
- pNew.nSrc = pNew.nAlloc = p.nSrc;
- for (int i = 0; i < p.nSrc; i++ )
- {
- pNew.a[i] = new SrcList_item();
- SrcList_item pNewItem = pNew.a[i];
- SrcList_item pOldItem = p.a[i];
- Table pTab;
- pNewItem.zDatabase = pOldItem.zDatabase;// sqlite3DbStrDup(db, pOldItem.zDatabase);
- pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName);
- pNewItem.zAlias = pOldItem.zAlias;// sqlite3DbStrDup(db, pOldItem.zAlias);
- pNewItem.jointype = pOldItem.jointype;
- pNewItem.iCursor = pOldItem.iCursor;
- pNewItem.isPopulated = pOldItem.isPopulated;
- pNewItem.zIndex = pOldItem.zIndex;// sqlite3DbStrDup( db, pOldItem.zIndex );
- pNewItem.notIndexed = pOldItem.notIndexed;
- pNewItem.pIndex = pOldItem.pIndex;
- pTab = pNewItem.pTab = pOldItem.pTab;
- if ( pTab != null )
- {
- pTab.nRef++;
+ /*
+ ** If cursors, triggers, views and subqueries are all omitted from
+ ** the build, then none of the following routines, except for
+ ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
+ ** called with a NULL argument.
+ */
+#if !SQLITE_OMIT_VIEW || !SQLITE_OMIT_TRIGGER || !SQLITE_OMIT_SUBQUERY
+ static SrcList sqlite3SrcListDup(sqlite3 db, SrcList p, int flags) {
+ SrcList pNew;
+ int nByte;
+ if (p == null)
+ return null;
+ //nByte = sizeof(*p) + (p.nSrc>0 ? sizeof(p.a[0]) * (p.nSrc-1) : 0);
+ pNew = new SrcList();//sqlite3DbMallocRaw(db, nByte );
+ if (p.nSrc > 0)
+ pNew.a = new SrcList_item[p.nSrc];
+ if (pNew == null)
+ return null;
+ pNew.nSrc = pNew.nAlloc = p.nSrc;
+ for (int i = 0; i < p.nSrc; i++) {
+ pNew.a[i] = new SrcList_item();
+ SrcList_item pNewItem = pNew.a[i];
+ SrcList_item pOldItem = p.a[i];
+ Table pTab;
+ pNewItem.zDatabase = pOldItem.zDatabase;// sqlite3DbStrDup(db, pOldItem.zDatabase);
+ pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName);
+ pNewItem.zAlias = pOldItem.zAlias;// sqlite3DbStrDup(db, pOldItem.zAlias);
+ pNewItem.jointype = pOldItem.jointype;
+ pNewItem.iCursor = pOldItem.iCursor;
+ pNewItem.isPopulated = pOldItem.isPopulated;
+ pNewItem.zIndex = pOldItem.zIndex;// sqlite3DbStrDup( db, pOldItem.zIndex );
+ pNewItem.notIndexed = pOldItem.notIndexed;
+ pNewItem.pIndex = pOldItem.pIndex;
+ pTab = pNewItem.pTab = pOldItem.pTab;
+ if (pTab != null) {
+ pTab.nRef++;
+ }
+ pNewItem.pSelect = sqlite3SelectDup(db, pOldItem.pSelect, flags);
+ pNewItem.pOn = sqlite3ExprDup(db, pOldItem.pOn, flags);
+ pNewItem.pUsing = sqlite3IdListDup(db, pOldItem.pUsing);
+ pNewItem.colUsed = pOldItem.colUsed;
+ }
+ return pNew;
}
- pNewItem.pSelect = sqlite3SelectDup( db, pOldItem.pSelect, flags );
- pNewItem.pOn = sqlite3ExprDup( db, pOldItem.pOn, flags );
- pNewItem.pUsing = sqlite3IdListDup( db, pOldItem.pUsing );
- pNewItem.colUsed = pOldItem.colUsed;
- }
- return pNew;
- }
- static IdList sqlite3IdListDup( sqlite3 db, IdList p )
- {
- IdList pNew;
- int i;
- if ( p == null )
- return null;
- pNew = new IdList();//sqlite3DbMallocRaw(db, sizeof(*pNew) );
- if ( pNew == null )
- return null;
- pNew.nId = pNew.nAlloc = p.nId;
- pNew.a = new IdList_item[p.nId];//sqlite3DbMallocRaw(db, p.nId*sizeof(p.a[0]) );
- if ( pNew.a == null )
- {
- sqlite3DbFree( db, ref pNew );
- return null;
- }
- for ( i = 0; i < p.nId; i++ )
- {
- pNew.a[i] = new IdList_item();
- IdList_item pNewItem = pNew.a[i];
- IdList_item pOldItem = p.a[i];
- pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName);
- pNewItem.idx = pOldItem.idx;
- }
- return pNew;
- }
+ static IdList sqlite3IdListDup(sqlite3 db, IdList p) {
+ IdList pNew;
+ int i;
+ if (p == null)
+ return null;
+ pNew = new IdList();//sqlite3DbMallocRaw(db, sizeof(*pNew) );
+ if (pNew == null)
+ return null;
+ pNew.nId = pNew.nAlloc = p.nId;
+ pNew.a = new IdList_item[p.nId];//sqlite3DbMallocRaw(db, p.nId*sizeof(p.a[0]) );
+ if (pNew.a == null) {
+ sqlite3DbFree(db, ref pNew);
+ return null;
+ }
+ for (i = 0; i < p.nId; i++) {
+ pNew.a[i] = new IdList_item();
+ IdList_item pNewItem = pNew.a[i];
+ IdList_item pOldItem = p.a[i];
+ pNewItem.zName = pOldItem.zName;// sqlite3DbStrDup(db, pOldItem.zName);
+ pNewItem.idx = pOldItem.idx;
+ }
+ return pNew;
+ }
- static Select sqlite3SelectDup( sqlite3 db, Select p, int flags )
- {
- Select pNew;
- if ( p == null )
- return null;
- pNew = new Select();//sqlite3DbMallocRaw(db, sizeof(*p) );
- //if ( pNew == null ) return null;
- pNew.pEList = sqlite3ExprListDup( db, p.pEList, flags );
- pNew.pSrc = sqlite3SrcListDup( db, p.pSrc, flags );
- pNew.pWhere = sqlite3ExprDup( db, p.pWhere, flags );
- pNew.pGroupBy = sqlite3ExprListDup( db, p.pGroupBy, flags );
- pNew.pHaving = sqlite3ExprDup( db, p.pHaving, flags );
- pNew.pOrderBy = sqlite3ExprListDup( db, p.pOrderBy, flags );
- pNew.op = p.op;
- pNew.pPrior = sqlite3SelectDup( db, p.pPrior, flags );
- pNew.pLimit = sqlite3ExprDup( db, p.pLimit, flags );
- pNew.pOffset = sqlite3ExprDup( db, p.pOffset, flags );
- pNew.iLimit = 0;
- pNew.iOffset = 0;
- pNew.selFlags = (u16)( p.selFlags & ~SF_UsesEphemeral );
- pNew.pRightmost = null;
- pNew.addrOpenEphm[0] = -1;
- pNew.addrOpenEphm[1] = -1;
- pNew.addrOpenEphm[2] = -1;
- return pNew;
- }
+ static Select sqlite3SelectDup(sqlite3 db, Select p, int flags) {
+ Select pNew;
+ if (p == null)
+ return null;
+ pNew = new Select();//sqlite3DbMallocRaw(db, sizeof(*p) );
+ //if ( pNew == null ) return null;
+ pNew.pEList = sqlite3ExprListDup(db, p.pEList, flags);
+ pNew.pSrc = sqlite3SrcListDup(db, p.pSrc, flags);
+ pNew.pWhere = sqlite3ExprDup(db, p.pWhere, flags);
+ pNew.pGroupBy = sqlite3ExprListDup(db, p.pGroupBy, flags);
+ pNew.pHaving = sqlite3ExprDup(db, p.pHaving, flags);
+ pNew.pOrderBy = sqlite3ExprListDup(db, p.pOrderBy, flags);
+ pNew.op = p.op;
+ pNew.pPrior = sqlite3SelectDup(db, p.pPrior, flags);
+ pNew.pLimit = sqlite3ExprDup(db, p.pLimit, flags);
+ pNew.pOffset = sqlite3ExprDup(db, p.pOffset, flags);
+ pNew.iLimit = 0;
+ pNew.iOffset = 0;
+ pNew.selFlags = (u16)(p.selFlags & ~SF_UsesEphemeral);
+ pNew.pRightmost = null;
+ pNew.addrOpenEphm[0] = -1;
+ pNew.addrOpenEphm[1] = -1;
+ pNew.addrOpenEphm[2] = -1;
+ return pNew;
+ }
#else
Select sqlite3SelectDup(sqlite3 db, Select p, int flags){
Debug.Assert( p==null );
@@ -1213,1212 +1065,1102 @@ Select sqlite3SelectDup(sqlite3 db, Select p, int flags){
#endif
- /*
-** Add a new element to the end of an expression list. If pList is
-** initially NULL, then create a new expression list.
-**
-** If a memory allocation error occurs, the entire list is freed and
-** NULL is returned. If non-NULL is returned, then it is guaranteed
-** that the new entry was successfully appended.
-*/
- // OVERLOADS, so I don't need to rewrite parse.c
- static ExprList sqlite3ExprListAppend( Parse pParse, int null_2, Expr pExpr )
- {
- return sqlite3ExprListAppend( pParse, null, pExpr );
- }
- static ExprList sqlite3ExprListAppend(
- Parse pParse, /* Parsing context */
- ExprList pList, /* List to which to append. Might be NULL */
- Expr pExpr /* Expression to be appended. Might be NULL */
- )
- {
- ////sqlite3 db = pParse.db;
- if ( pList == null )
- {
- pList = new ExprList(); //sqlite3DbMallocZero(db, ExprList).Length;
- //if ( pList == null )
- //{
- // goto no_mem;
- //}
- Debug.Assert( pList.nAlloc == 0 );
- }
- if ( pList.nAlloc <= pList.nExpr )
- {
- ExprList_item a;
- int n = pList.nAlloc * 2 + 4;
- //a = sqlite3DbRealloc(db, pList.a, n*sizeof(pList.a[0]));
- //if( a==0 ){
- // goto no_mem;
- //}
- Array.Resize( ref pList.a, n );// = a;
- pList.nAlloc = pList.a.Length;// sqlite3DbMallocSize(db, a)/sizeof(a[0]);
- }
- Debug.Assert( pList.a != null );
- if ( true )
- {
- pList.a[pList.nExpr] = new ExprList_item();
- //ExprList_item pItem = pList.a[pList.nExpr++];
- //pItem = new ExprList_item();//memset(pItem, 0, sizeof(*pItem));
- //pItem.pExpr = pExpr;
- pList.a[pList.nExpr++].pExpr = pExpr;
- }
- return pList;
-
- //no_mem:
- // /* Avoid leaking memory if malloc has failed. */
- // sqlite3ExprDelete( db, ref pExpr );
- // sqlite3ExprListDelete( db, ref pList );
- // return null;
- }
-
- /*
- ** Set the ExprList.a[].zName element of the most recently added item
- ** on the expression list.
- **
- ** pList might be NULL following an OOM error. But pName should never be
- ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag
- ** is set.
- */
- static void sqlite3ExprListSetName(
- Parse pParse, /* Parsing context */
- ExprList pList, /* List to which to add the span. */
- Token pName, /* Name to be added */
- int dequote /* True to cause the name to be dequoted */
- )
- {
- Debug.Assert( pList != null /* || pParse.db.mallocFailed != 0 */ );
- if ( pList != null )
- {
- ExprList_item pItem;
- Debug.Assert( pList.nExpr > 0 );
- pItem = pList.a[pList.nExpr - 1];
- Debug.Assert( pItem.zName == null );
- pItem.zName = pName.z.Substring( 0, pName.n );//sqlite3DbStrNDup(pParse.db, pName.z, pName.n);
- if ( dequote != 0 && !string.IsNullOrEmpty( pItem.zName ) )
- sqlite3Dequote( ref pItem.zName );
- }
- }
-
- /*
- ** Set the ExprList.a[].zSpan element of the most recently added item
- ** on the expression list.
+ /*
+ ** Add a new element to the end of an expression list. If pList is
+ ** initially NULL, then create a new expression list.
**
- ** pList might be NULL following an OOM error. But pSpan should never be
- ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag
- ** is set.
+ ** If a memory allocation error occurs, the entire list is freed and
+ ** NULL is returned. If non-NULL is returned, then it is guaranteed
+ ** that the new entry was successfully appended.
*/
- static void sqlite3ExprListSetSpan(
- Parse pParse, /* Parsing context */
- ExprList pList, /* List to which to add the span. */
- ExprSpan pSpan /* The span to be added */
- )
- {
- sqlite3 db = pParse.db;
- Debug.Assert( pList != null /*|| db.mallocFailed != 0 */ );
- if ( pList != null )
- {
- ExprList_item pItem = pList.a[pList.nExpr - 1];
- Debug.Assert( pList.nExpr > 0 );
- Debug.Assert( /* db.mallocFailed != 0 || */ pItem.pExpr == pSpan.pExpr );
- sqlite3DbFree( db, ref pItem.zSpan );
- pItem.zSpan = pSpan.zStart.Substring( 0, pSpan.zStart.Length <= pSpan.zEnd.Length ? pSpan.zStart.Length : pSpan.zStart.Length - pSpan.zEnd.Length );// sqlite3DbStrNDup( db, pSpan.zStart,
- //(int)( pSpan.zEnd- pSpan.zStart) );
- }
- }
-
- /*
- ** If the expression list pEList contains more than iLimit elements,
- ** leave an error message in pParse.
- */
- static void sqlite3ExprListCheckLength(
- Parse pParse,
- ExprList pEList,
- string zObject
- )
- {
- int mx = pParse.db.aLimit[SQLITE_LIMIT_COLUMN];
- testcase( pEList != null && pEList.nExpr == mx );
- testcase( pEList != null && pEList.nExpr == mx + 1 );
- if ( pEList != null && pEList.nExpr > mx )
- {
- sqlite3ErrorMsg( pParse, "too many columns in %s", zObject );
- }
- }
-
-
- /*
- ** Delete an entire expression list.
- */
- static void sqlite3ExprListDelete( sqlite3 db, ref ExprList pList )
- {
- int i;
- ExprList_item pItem;
- if ( pList == null )
- return;
- Debug.Assert( pList.a != null || ( pList.nExpr == 0 && pList.nAlloc == 0 ) );
- Debug.Assert( pList.nExpr <= pList.nAlloc );
- for ( i = 0; i < pList.nExpr; i++ )
- {
- if ( ( pItem = pList.a[i] ) != null )
- {
- sqlite3ExprDelete( db, ref pItem.pExpr );
- sqlite3DbFree( db, ref pItem.zName );
- sqlite3DbFree( db, ref pItem.zSpan );
+ // OVERLOADS, so I don't need to rewrite parse.c
+ static ExprList sqlite3ExprListAppend(Parse pParse, int null_2, Expr pExpr) {
+ return sqlite3ExprListAppend(pParse, null, pExpr);
}
- }
- sqlite3DbFree( db, ref pList.a );
- sqlite3DbFree( db, ref pList );
- }
-
- /*
- ** These routines are Walker callbacks. Walker.u.pi is a pointer
- ** to an integer. These routines are checking an expression to see
- ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
- ** not constant.
- **
- ** These callback routines are used to implement the following:
- **
- ** sqlite3ExprIsConstant()
- ** sqlite3ExprIsConstantNotJoin()
- ** sqlite3ExprIsConstantOrFunction()
- **
- */
- static int exprNodeIsConstant( Walker pWalker, ref Expr pExpr )
- {
- /* If pWalker.u.i is 3 then any term of the expression that comes from
- ** the ON or USING clauses of a join disqualifies the expression
- ** from being considered constant. */
- if ( pWalker.u.i == 3 && ExprHasAnyProperty( pExpr, EP_FromJoin ) )
- {
- pWalker.u.i = 0;
- return WRC_Abort;
- }
-
- switch ( pExpr.op )
- {
- /* Consider functions to be constant if all their arguments are constant
- ** and pWalker.u.i==2 */
- case TK_FUNCTION:
- if ( ( pWalker.u.i ) == 2 )
- return 0;
- goto case TK_ID;
- /* Fall through */
- case TK_ID:
- case TK_COLUMN:
- case TK_AGG_FUNCTION:
- case TK_AGG_COLUMN:
- testcase( pExpr.op == TK_ID );
- testcase( pExpr.op == TK_COLUMN );
- testcase( pExpr.op == TK_AGG_FUNCTION );
- testcase( pExpr.op == TK_AGG_COLUMN );
- pWalker.u.i = 0;
- return WRC_Abort;
- default:
- testcase( pExpr.op == TK_SELECT ); /* selectNodeIsConstant will disallow */
- testcase( pExpr.op == TK_EXISTS ); /* selectNodeIsConstant will disallow */
- return WRC_Continue;
- }
- }
-
- static int selectNodeIsConstant( Walker pWalker, Select NotUsed )
- {
- UNUSED_PARAMETER( NotUsed );
- pWalker.u.i = 0;
- return WRC_Abort;
- }
- static int exprIsConst( Expr p, int initFlag )
- {
- Walker w = new Walker();
- w.u.i = initFlag;
- w.xExprCallback = exprNodeIsConstant;
- w.xSelectCallback = selectNodeIsConstant;
- sqlite3WalkExpr( w, ref p );
- return w.u.i;
- }
-
- /*
- ** Walk an expression tree. Return 1 if the expression is constant
- ** and 0 if it involves variables or function calls.
- **
- ** For the purposes of this function, a double-quoted string (ex: "abc")
- ** is considered a variable but a single-quoted string (ex: 'abc') is
- ** a constant.
- */
- static int sqlite3ExprIsConstant( Expr p )
- {
- return exprIsConst( p, 1 );
- }
+ static ExprList sqlite3ExprListAppend(
+ Parse pParse, /* Parsing context */
+ ExprList pList, /* List to which to append. Might be NULL */
+ Expr pExpr /* Expression to be appended. Might be NULL */
+ ) {
+ ////sqlite3 db = pParse.db;
+ if (pList == null) {
+ pList = new ExprList(); //sqlite3DbMallocZero(db, ExprList).Length;
+ //if ( pList == null )
+ //{
+ // goto no_mem;
+ //}
+ Debug.Assert(pList.nAlloc == 0);
+ }
+ if (pList.nAlloc <= pList.nExpr) {
+ ExprList_item a;
+ int n = pList.nAlloc * 2 + 4;
+ //a = sqlite3DbRealloc(db, pList.a, n*sizeof(pList.a[0]));
+ //if( a==0 ){
+ // goto no_mem;
+ //}
+ Array.Resize(ref pList.a, n);// = a;
+ pList.nAlloc = pList.a.Length;// sqlite3DbMallocSize(db, a)/sizeof(a[0]);
+ }
+ Debug.Assert(pList.a != null);
+ if (true) {
+ pList.a[pList.nExpr] = new ExprList_item();
+ //ExprList_item pItem = pList.a[pList.nExpr++];
+ //pItem = new ExprList_item();//memset(pItem, 0, sizeof(*pItem));
+ //pItem.pExpr = pExpr;
+ pList.a[pList.nExpr++].pExpr = pExpr;
+ }
+ return pList;
- /*
- ** Walk an expression tree. Return 1 if the expression is constant
- ** that does no originate from the ON or USING clauses of a join.
- ** Return 0 if it involves variables or function calls or terms from
- ** an ON or USING clause.
- */
- static int sqlite3ExprIsConstantNotJoin( Expr p )
- {
- return exprIsConst( p, 3 );
- }
+ //no_mem:
+ // /* Avoid leaking memory if malloc has failed. */
+ // sqlite3ExprDelete( db, ref pExpr );
+ // sqlite3ExprListDelete( db, ref pList );
+ // return null;
+ }
- /*
- ** Walk an expression tree. Return 1 if the expression is constant
- ** or a function call with constant arguments. Return and 0 if there
- ** are any variables.
- **
- ** For the purposes of this function, a double-quoted string (ex: "abc")
- ** is considered a variable but a single-quoted string (ex: 'abc') is
- ** a constant.
- */
- static int sqlite3ExprIsConstantOrFunction( Expr p )
- {
- return exprIsConst( p, 2 );
- }
+ /*
+ ** Set the ExprList.a[].zName element of the most recently added item
+ ** on the expression list.
+ **
+ ** pList might be NULL following an OOM error. But pName should never be
+ ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag
+ ** is set.
+ */
+ static void sqlite3ExprListSetName(
+ Parse pParse, /* Parsing context */
+ ExprList pList, /* List to which to add the span. */
+ Token pName, /* Name to be added */
+ int dequote /* True to cause the name to be dequoted */
+ ) {
+ Debug.Assert(pList != null /* || pParse.db.mallocFailed != 0 */ );
+ if (pList != null) {
+ ExprList_item pItem;
+ Debug.Assert(pList.nExpr > 0);
+ pItem = pList.a[pList.nExpr - 1];
+ Debug.Assert(pItem.zName == null);
+ pItem.zName = pName.z.Substring(0, pName.n);//sqlite3DbStrNDup(pParse.db, pName.z, pName.n);
+ if (dequote != 0 && !string.IsNullOrEmpty(pItem.zName))
+ sqlite3Dequote(ref pItem.zName);
+ }
+ }
- /*
- ** If the expression p codes a constant integer that is small enough
- ** to fit in a 32-bit integer, return 1 and put the value of the integer
- ** in pValue. If the expression is not an integer or if it is too big
- ** to fit in a signed 32-bit integer, return 0 and leave pValue unchanged.
- */
- static int sqlite3ExprIsInteger( Expr p, ref int pValue )
- {
- int rc = 0;
-
- /* If an expression is an integer literal that fits in a signed 32-bit
- ** integer, then the EP_IntValue flag will have already been set */
- Debug.Assert( p.op != TK_INTEGER || ( p.flags & EP_IntValue ) != 0
- || !sqlite3GetInt32( p.u.zToken, ref rc ) );
-
- if ( ( p.flags & EP_IntValue ) != 0 )
- {
- pValue = (int)p.u.iValue;
- return 1;
- }
- switch ( p.op )
- {
- case TK_UPLUS:
- {
- rc = sqlite3ExprIsInteger( p.pLeft, ref pValue );
- break;
- }
- case TK_UMINUS:
- {
- int v = 0;
- if ( sqlite3ExprIsInteger( p.pLeft, ref v ) != 0 )
- {
- pValue = -v;
- rc = 1;
+ /*
+ ** Set the ExprList.a[].zSpan element of the most recently added item
+ ** on the expression list.
+ **
+ ** pList might be NULL following an OOM error. But pSpan should never be
+ ** NULL. If a memory allocation fails, the pParse.db.mallocFailed flag
+ ** is set.
+ */
+ static void sqlite3ExprListSetSpan(
+ Parse pParse, /* Parsing context */
+ ExprList pList, /* List to which to add the span. */
+ ExprSpan pSpan /* The span to be added */
+ ) {
+ sqlite3 db = pParse.db;
+ Debug.Assert(pList != null /*|| db.mallocFailed != 0 */ );
+ if (pList != null) {
+ ExprList_item pItem = pList.a[pList.nExpr - 1];
+ Debug.Assert(pList.nExpr > 0);
+ Debug.Assert( /* db.mallocFailed != 0 || */ pItem.pExpr == pSpan.pExpr);
+ sqlite3DbFree(db, ref pItem.zSpan);
+ pItem.zSpan = pSpan.zStart.Substring(0, pSpan.zStart.Length <= pSpan.zEnd.Length ? pSpan.zStart.Length : pSpan.zStart.Length - pSpan.zEnd.Length);// sqlite3DbStrNDup( db, pSpan.zStart,
+ //(int)( pSpan.zEnd- pSpan.zStart) );
}
- break;
- }
- default:
- break;
- }
- return rc;
- }
+ }
- /*
- ** Return FALSE if there is no chance that the expression can be NULL.
- **
- ** If the expression might be NULL or if the expression is too complex
- ** to tell return TRUE.
- **
- ** This routine is used as an optimization, to skip OP_IsNull opcodes
- ** when we know that a value cannot be NULL. Hence, a false positive
- ** (returning TRUE when in fact the expression can never be NULL) might
- ** be a small performance hit but is otherwise harmless. On the other
- ** hand, a false negative (returning FALSE when the result could be NULL)
- ** will likely result in an incorrect answer. So when in doubt, return
- ** TRUE.
- */
- static int sqlite3ExprCanBeNull( Expr p )
- {
- u8 op;
- while ( p.op == TK_UPLUS || p.op == TK_UMINUS )
- {
- p = p.pLeft;
- }
- op = p.op;
- if ( op == TK_REGISTER )
- op = p.op2;
- switch ( op )
- {
- case TK_INTEGER:
- case TK_STRING:
- case TK_FLOAT:
- case TK_BLOB:
- return 0;
- default:
- return 1;
- }
- }
+ /*
+ ** If the expression list pEList contains more than iLimit elements,
+ ** leave an error message in pParse.
+ */
+ static void sqlite3ExprListCheckLength(
+ Parse pParse,
+ ExprList pEList,
+ string zObject
+ ) {
+ int mx = pParse.db.aLimit[SQLITE_LIMIT_COLUMN];
+ testcase(pEList != null && pEList.nExpr == mx);
+ testcase(pEList != null && pEList.nExpr == mx + 1);
+ if (pEList != null && pEList.nExpr > mx) {
+ sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
+ }
+ }
- /*
- ** Generate an OP_IsNull instruction that tests register iReg and jumps
- ** to location iDest if the value in iReg is NULL. The value in iReg
- ** was computed by pExpr. If we can look at pExpr at compile-time and
- ** determine that it can never generate a NULL, then the OP_IsNull operation
- ** can be omitted.
- */
- static void sqlite3ExprCodeIsNullJump(
- Vdbe v, /* The VDBE under construction */
- Expr pExpr, /* Only generate OP_IsNull if this expr can be NULL */
- int iReg, /* Test the value in this register for NULL */
- int iDest /* Jump here if the value is null */
- )
- {
- if ( sqlite3ExprCanBeNull( pExpr ) != 0 )
- {
- sqlite3VdbeAddOp2( v, OP_IsNull, iReg, iDest );
- }
- }
- /*
- ** Return TRUE if the given expression is a constant which would be
- ** unchanged by OP_Affinity with the affinity given in the second
- ** argument.
- **
- ** This routine is used to determine if the OP_Affinity operation
- ** can be omitted. When in doubt return FALSE. A false negative
- ** is harmless. A false positive, however, can result in the wrong
- ** answer.
- */
- static int sqlite3ExprNeedsNoAffinityChange( Expr p, char aff )
- {
- u8 op;
- if ( aff == SQLITE_AFF_NONE )
- return 1;
- while ( p.op == TK_UPLUS || p.op == TK_UMINUS )
- {
- p = p.pLeft;
- }
- op = p.op;
- if ( op == TK_REGISTER )
- op = p.op2;
- switch ( op )
- {
- case TK_INTEGER:
- {
- return ( aff == SQLITE_AFF_INTEGER || aff == SQLITE_AFF_NUMERIC ) ? 1 : 0;
- }
- case TK_FLOAT:
- {
- return ( aff == SQLITE_AFF_REAL || aff == SQLITE_AFF_NUMERIC ) ? 1 : 0;
- }
- case TK_STRING:
- {
- return ( aff == SQLITE_AFF_TEXT ) ? 1 : 0;
- }
- case TK_BLOB:
- {
- return 1;
- }
- case TK_COLUMN:
- {
- Debug.Assert( p.iTable >= 0 ); /* p cannot be part of a CHECK constraint */
- return ( p.iColumn < 0
- && ( aff == SQLITE_AFF_INTEGER || aff == SQLITE_AFF_NUMERIC ) ) ? 1 : 0;
- }
- default:
- {
- return 0;
- }
- }
- }
+ /*
+ ** Delete an entire expression list.
+ */
+ static void sqlite3ExprListDelete(sqlite3 db, ref ExprList pList) {
+ int i;
+ ExprList_item pItem;
+ if (pList == null)
+ return;
+ Debug.Assert(pList.a != null || (pList.nExpr == 0 && pList.nAlloc == 0));
+ Debug.Assert(pList.nExpr <= pList.nAlloc);
+ for (i = 0; i < pList.nExpr; i++) {
+ if ((pItem = pList.a[i]) != null) {
+ sqlite3ExprDelete(db, ref pItem.pExpr);
+ sqlite3DbFree(db, ref pItem.zName);
+ sqlite3DbFree(db, ref pItem.zSpan);
+ }
+ }
+ sqlite3DbFree(db, ref pList.a);
+ sqlite3DbFree(db, ref pList);
+ }
- /*
- ** Return TRUE if the given string is a row-id column name.
- */
- static bool sqlite3IsRowid( string z )
- {
- if ( z.Equals( "_ROWID_", StringComparison.OrdinalIgnoreCase ) )
- return true;
- if ( z.Equals( "ROWID", StringComparison.OrdinalIgnoreCase ) )
- return true;
- if ( z.Equals( "OID", StringComparison.OrdinalIgnoreCase ) )
- return true;
- return false;
- }
+ /*
+ ** These routines are Walker callbacks. Walker.u.pi is a pointer
+ ** to an integer. These routines are checking an expression to see
+ ** if it is a constant. Set *Walker.u.pi to 0 if the expression is
+ ** not constant.
+ **
+ ** These callback routines are used to implement the following:
+ **
+ ** sqlite3ExprIsConstant()
+ ** sqlite3ExprIsConstantNotJoin()
+ ** sqlite3ExprIsConstantOrFunction()
+ **
+ */
+ static int exprNodeIsConstant(Walker pWalker, ref Expr pExpr) {
+ /* If pWalker.u.i is 3 then any term of the expression that comes from
+ ** the ON or USING clauses of a join disqualifies the expression
+ ** from being considered constant. */
+ if (pWalker.u.i == 3 && ExprHasAnyProperty(pExpr, EP_FromJoin)) {
+ pWalker.u.i = 0;
+ return WRC_Abort;
+ }
+ switch (pExpr.op) {
+ /* Consider functions to be constant if all their arguments are constant
+ ** and pWalker.u.i==2 */
+ case TK_FUNCTION:
+ if ((pWalker.u.i) == 2)
+ return 0;
+ goto case TK_ID;
+ /* Fall through */
+ case TK_ID:
+ case TK_COLUMN:
+ case TK_AGG_FUNCTION:
+ case TK_AGG_COLUMN:
+ testcase(pExpr.op == TK_ID);
+ testcase(pExpr.op == TK_COLUMN);
+ testcase(pExpr.op == TK_AGG_FUNCTION);
+ testcase(pExpr.op == TK_AGG_COLUMN);
+ pWalker.u.i = 0;
+ return WRC_Abort;
+ default:
+ testcase(pExpr.op == TK_SELECT); /* selectNodeIsConstant will disallow */
+ testcase(pExpr.op == TK_EXISTS); /* selectNodeIsConstant will disallow */
+ return WRC_Continue;
+ }
+ }
- /*
- ** Return true if we are able to the IN operator optimization on a
- ** query of the form
- **
- ** x IN (SELECT ...)
- **
- ** Where the SELECT... clause is as specified by the parameter to this
- ** routine.
- **
- ** The Select object passed in has already been preprocessed and no
- ** errors have been found.
- */
-#if !SQLITE_OMIT_SUBQUERY
- static int isCandidateForInOpt( Select p )
- {
- SrcList pSrc;
- ExprList pEList;
- Table pTab;
- if ( p == null )
- return 0; /* right-hand side of IN is SELECT */
- if ( p.pPrior != null )
- return 0; /* Not a compound SELECT */
- if ( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) != 0 )
- {
- testcase( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Distinct );
- testcase( ( p.selFlags & ( SF_Distinct | SF_Aggregate ) ) == SF_Aggregate );
- return 0; /* No DISTINCT keyword and no aggregate functions */
- }
- Debug.Assert( p.pGroupBy == null ); /* Has no GROUP BY clause */
- if ( p.pLimit != null )
- return 0; /* Has no LIMIT clause */
- Debug.Assert( p.pOffset == null ); /* No LIMIT means no OFFSET */
-
- if ( p.pWhere != null )
- return 0; /* Has no WHERE clause */
- pSrc = p.pSrc;
- Debug.Assert( pSrc != null );
- if ( pSrc.nSrc != 1 )
- return 0; /* Single term in FROM clause */
- if ( pSrc.a[0].pSelect != null )
- return 0; /* FROM is not a subquery or view */
- pTab = pSrc.a[0].pTab;
- if ( NEVER( pTab == null ) )
- return 0;
- Debug.Assert( pTab.pSelect == null ); /* FROM clause is not a view */
- if ( IsVirtual( pTab ) )
- return 0; /* FROM clause not a virtual table */
- pEList = p.pEList;
- if ( pEList.nExpr != 1 )
- return 0; /* One column in the result set */
- if ( pEList.a[0].pExpr.op != TK_COLUMN )
- return 0; /* Result is a column */
- return 1;
- }
-#endif //* SQLITE_OMIT_SUBQUERY */
+ static int selectNodeIsConstant(Walker pWalker, Select NotUsed) {
+ UNUSED_PARAMETER(NotUsed);
+ pWalker.u.i = 0;
+ return WRC_Abort;
+ }
+ static int exprIsConst(Expr p, int initFlag) {
+ Walker w = new Walker();
+ w.u.i = initFlag;
+ w.xExprCallback = exprNodeIsConstant;
+ w.xSelectCallback = selectNodeIsConstant;
+ sqlite3WalkExpr(w, ref p);
+ return w.u.i;
+ }
- /*
-** This function is used by the implementation of the IN (...) operator.
-** It's job is to find or create a b-tree structure that may be used
-** either to test for membership of the (...) set or to iterate through
-** its members, skipping duplicates.
-**
-** The index of the cursor opened on the b-tree (database table, database index
-** or ephermal table) is stored in pX->iTable before this function returns.
-** The returned value of this function indicates the b-tree type, as follows:
-**
-** IN_INDEX_ROWID - The cursor was opened on a database table.
-** IN_INDEX_INDEX - The cursor was opened on a database index.
-** IN_INDEX_EPH - The cursor was opened on a specially created and
-** populated epheremal table.
-**
-** An existing b-tree may only be used if the SELECT is of the simple
-** form:
-**
-** SELECT FROM
-**
-** If the prNotFound parameter is 0, then the b-tree will be used to iterate
-** through the set members, skipping any duplicates. In this case an
-** epheremal table must be used unless the selected is guaranteed
-** to be unique - either because it is an INTEGER PRIMARY KEY or it
-** has a UNIQUE constraint or UNIQUE index.
-**
-** If the prNotFound parameter is not 0, then the b-tree will be used
-** for fast set membership tests. In this case an epheremal table must
-** be used unless is an INTEGER PRIMARY KEY or an index can
-** be found with as its left-most column.
-**
-** When the b-tree is being used for membership tests, the calling function
-** needs to know whether or not the structure contains an SQL NULL
-** value in order to correctly evaluate expressions like "X IN (Y, Z)".
-** If there is any chance that the (...) might contain a NULL value at
-** runtime, then a register is allocated and the register number written
-** to *prNotFound. If there is no chance that the (...) contains a
-** NULL value, then *prNotFound is left unchanged.
-**
-** If a register is allocated and its location stored in *prNotFound, then
-** its initial value is NULL. If the (...) does not remain constant
-** for the duration of the query (i.e. the SELECT within the (...)
-** is a correlated subquery) then the value of the allocated register is
-** reset to NULL each time the subquery is rerun. This allows the
-** caller to use vdbe code equivalent to the following:
-**
-** if( register==NULL ){
-** has_null =
-** register = 1
-** }
-**
-** in order to avoid running the
-** test more often than is necessary.
-*/
-#if !SQLITE_OMIT_SUBQUERY
- static int sqlite3FindInIndex( Parse pParse, Expr pX, ref int prNotFound )
- {
- Select p; /* SELECT to the right of IN operator */
- int eType = 0; /* Type of RHS table. IN_INDEX_* */
- int iTab = pParse.nTab++; /* Cursor of the RHS table */
- bool mustBeUnique = ( prNotFound != 0 ); /* True if RHS must be unique */
-
- Debug.Assert( pX.op == TK_IN );
-
- /* Check to see if an existing table or index can be used to
- ** satisfy the query. This is preferable to generating a new
- ** ephemeral table.
- */
- p = ( ExprHasProperty( pX, EP_xIsSelect ) ? pX.x.pSelect : null );
- if ( ALWAYS( pParse.nErr == 0 ) && isCandidateForInOpt( p ) != 0 )
- {
- sqlite3 db = pParse.db; /* Database connection */
- Expr pExpr = p.pEList.a[0].pExpr; /* Expression */
- int iCol = pExpr.iColumn; /* Index of column */
- Vdbe v = sqlite3GetVdbe( pParse ); /* Virtual machine being coded */
- Table pTab = p.pSrc.a[0].pTab; /* Table
. */
- int iDb; /* Database idx for pTab */
-
- /* Code an OP_VerifyCookie and OP_TableLock for
. */
- iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
- sqlite3CodeVerifySchema( pParse, iDb );
- sqlite3TableLock( pParse, iDb, pTab.tnum, 0, pTab.zName );
-
- /* This function is only called from two places. In both cases the vdbe
- ** has already been allocated. So assume sqlite3GetVdbe() is always
- ** successful here.
+ /*
+ ** Walk an expression tree. Return 1 if the expression is constant
+ ** and 0 if it involves variables or function calls.
+ **
+ ** For the purposes of this function, a double-quoted string (ex: "abc")
+ ** is considered a variable but a single-quoted string (ex: 'abc') is
+ ** a constant.
*/
- Debug.Assert( v != null );
- if ( iCol < 0 )
- {
- int iMem = ++pParse.nMem;
- int iAddr;
-
- iAddr = sqlite3VdbeAddOp1( v, OP_If, iMem );
- sqlite3VdbeAddOp2( v, OP_Integer, 1, iMem );
+ static int sqlite3ExprIsConstant(Expr p) {
+ return exprIsConst(p, 1);
+ }
- sqlite3OpenTable( pParse, iTab, iDb, pTab, OP_OpenRead );
- eType = IN_INDEX_ROWID;
+ /*
+ ** Walk an expression tree. Return 1 if the expression is constant
+ ** that does no originate from the ON or USING clauses of a join.
+ ** Return 0 if it involves variables or function calls or terms from
+ ** an ON or USING clause.
+ */
+ static int sqlite3ExprIsConstantNotJoin(Expr p) {
+ return exprIsConst(p, 3);
+ }
- sqlite3VdbeJumpHere( v, iAddr );
+ /*
+ ** Walk an expression tree. Return 1 if the expression is constant
+ ** or a function call with constant arguments. Return and 0 if there
+ ** are any variables.
+ **
+ ** For the purposes of this function, a double-quoted string (ex: "abc")
+ ** is considered a variable but a single-quoted string (ex: 'abc') is
+ ** a constant.
+ */
+ static int sqlite3ExprIsConstantOrFunction(Expr p) {
+ return exprIsConst(p, 2);
}
- else
- {
- Index pIdx; /* Iterator variable */
- /* The collation sequence used by the comparison. If an index is to
- ** be used in place of a temp.table, it must be ordered according
- ** to this collation sequence. */
- CollSeq pReq = sqlite3BinaryCompareCollSeq( pParse, pX.pLeft, pExpr );
-
- /* Check that the affinity that will be used to perform the
- ** comparison is the same as the affinity of the column. If
- ** it is not, it is not possible to use any index.
- */
- char aff = comparisonAffinity( pX );
- bool affinity_ok = ( pTab.aCol[iCol].affinity == aff || aff == SQLITE_AFF_NONE );
-
- for ( pIdx = pTab.pIndex; pIdx != null && eType == 0 && affinity_ok; pIdx = pIdx.pNext )
- {
- if ( ( pIdx.aiColumn[0] == iCol )
- && ( sqlite3FindCollSeq( db, ENC( db ), pIdx.azColl[0], 0 ) == pReq )
- && ( mustBeUnique == false || ( pIdx.nColumn == 1 && pIdx.onError != OE_None ) )
- )
- {
- int iMem = ++pParse.nMem;
- int iAddr;
- KeyInfo pKey;
- pKey = sqlite3IndexKeyinfo( pParse, pIdx );
+ /*
+ ** If the expression p codes a constant integer that is small enough
+ ** to fit in a 32-bit integer, return 1 and put the value of the integer
+ ** in pValue. If the expression is not an integer or if it is too big
+ ** to fit in a signed 32-bit integer, return 0 and leave pValue unchanged.
+ */
+ static int sqlite3ExprIsInteger(Expr p, ref int pValue) {
+ int rc = 0;
- iAddr = sqlite3VdbeAddOp1( v, OP_If, iMem );
- sqlite3VdbeAddOp2( v, OP_Integer, 1, iMem );
+ /* If an expression is an integer literal that fits in a signed 32-bit
+ ** integer, then the EP_IntValue flag will have already been set */
+ Debug.Assert(p.op != TK_INTEGER || (p.flags & EP_IntValue) != 0
+ || !sqlite3GetInt32(p.u.zToken, ref rc));
- sqlite3VdbeAddOp4( v, OP_OpenRead, iTab, pIdx.tnum, iDb,
- pKey, P4_KEYINFO_HANDOFF );
-#if SQLITE_DEBUG
- VdbeComment( v, "%s", pIdx.zName );
-#endif
- eType = IN_INDEX_INDEX;
-
- sqlite3VdbeJumpHere( v, iAddr );
- if ( //prNotFound != null && -- always exists under C#
- pTab.aCol[iCol].notNull == 0 )
- {
- prNotFound = ++pParse.nMem;
- }
+ if ((p.flags & EP_IntValue) != 0) {
+ pValue = (int)p.u.iValue;
+ return 1;
}
- }
+ switch (p.op) {
+ case TK_UPLUS: {
+ rc = sqlite3ExprIsInteger(p.pLeft, ref pValue);
+ break;
+ }
+ case TK_UMINUS: {
+ int v = 0;
+ if (sqlite3ExprIsInteger(p.pLeft, ref v) != 0) {
+ pValue = -v;
+ rc = 1;
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ return rc;
}
- }
- if ( eType == 0 )
- {
- /* Could not found an existing table or index to use as the RHS b-tree.
- ** We will have to generate an ephemeral table to do the job.
+ /*
+ ** Return FALSE if there is no chance that the expression can be NULL.
+ **
+ ** If the expression might be NULL or if the expression is too complex
+ ** to tell return TRUE.
+ **
+ ** This routine is used as an optimization, to skip OP_IsNull opcodes
+ ** when we know that a value cannot be NULL. Hence, a false positive
+ ** (returning TRUE when in fact the expression can never be NULL) might
+ ** be a small performance hit but is otherwise harmless. On the other
+ ** hand, a false negative (returning FALSE when the result could be NULL)
+ ** will likely result in an incorrect answer. So when in doubt, return
+ ** TRUE.
*/
- double savedNQueryLoop = pParse.nQueryLoop;
- int rMayHaveNull = 0;
- eType = IN_INDEX_EPH;
- if ( prNotFound != -1 ) // Klude to show prNotFound not available
- {
- prNotFound = rMayHaveNull = ++pParse.nMem;
- }
- else
- {
- testcase( pParse.nQueryLoop > (double)1 );
- pParse.nQueryLoop = (double)1;
- if ( pX.pLeft.iColumn < 0 && !ExprHasAnyProperty( pX, EP_xIsSelect ) )
- {
- eType = IN_INDEX_ROWID;
- }
+ static int sqlite3ExprCanBeNull(Expr p) {
+ u8 op;
+ while (p.op == TK_UPLUS || p.op == TK_UMINUS) {
+ p = p.pLeft;
+ }
+ op = p.op;
+ if (op == TK_REGISTER)
+ op = p.op2;
+ switch (op) {
+ case TK_INTEGER:
+ case TK_STRING:
+ case TK_FLOAT:
+ case TK_BLOB:
+ return 0;
+ default:
+ return 1;
+ }
}
- sqlite3CodeSubselect( pParse, pX, rMayHaveNull, eType == IN_INDEX_ROWID );
- pParse.nQueryLoop = savedNQueryLoop;
- }
- else
- {
- pX.iTable = iTab;
- }
- return eType;
- }
-#endif
-
- /*
-** Generate code for scalar subqueries used as a subquery expression, EXISTS,
-** or IN operators. Examples:
-**
-** (SELECT a FROM b) -- subquery
-** EXISTS (SELECT a FROM b) -- EXISTS subquery
-** x IN (4,5,11) -- IN operator with list on right-hand side
-** x IN (SELECT a FROM b) -- IN operator with subquery on the right
-**
-** The pExpr parameter describes the expression that contains the IN
-** operator or subquery.
-**
-** If parameter isRowid is non-zero, then expression pExpr is guaranteed
-** to be of the form " IN (?, ?, ?)", where is a reference
-** to some integer key column of a table B-Tree. In this case, use an
-** intkey B-Tree to store the set of IN(...) values instead of the usual
-** (slower) variable length keys B-Tree.
-**
-** If rMayHaveNull is non-zero, that means that the operation is an IN
-** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
-** Furthermore, the IN is in a WHERE clause and that we really want
-** to iterate over the RHS of the IN operator in order to quickly locate
-** all corresponding LHS elements. All this routine does is initialize
-** the register given by rMayHaveNull to NULL. Calling routines will take
-** care of changing this register value to non-NULL if the RHS is NULL-free.
-**
-** If rMayHaveNull is zero, that means that the subquery is being used
-** for membership testing only. There is no need to initialize any
-** registers to indicate the presense or absence of NULLs on the RHS.
-**
-** For a SELECT or EXISTS operator, return the register that holds the
-** result. For IN operators or if an error occurs, the return value is 0.
-*/
-#if !SQLITE_OMIT_SUBQUERY
- static int sqlite3CodeSubselect(
- Parse pParse, /* Parsing context */
- Expr pExpr, /* The IN, SELECT, or EXISTS operator */
- int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
- bool isRowid /* If true, LHS of IN operator is a rowid */
- )
- {
- int testAddr = 0; /* One-time test address */
- int rReg = 0; /* Register storing resulting */
- Vdbe v = sqlite3GetVdbe( pParse );
- if ( NEVER( v == null ) )
- return 0;
- sqlite3ExprCachePush( pParse );
-
- /* This code must be run in its entirety every time it is encountered
- ** if any of the following is true:
- **
- ** * The right-hand side is a correlated subquery
- ** * The right-hand side is an expression list containing variables
- ** * We are inside a trigger
- **
- ** If all of the above are false, then we can run this code just once
- ** save the results, and reuse the same result on subsequent invocations.
- */
- if ( !ExprHasAnyProperty( pExpr, EP_VarSelect ) && null == pParse.pTriggerTab )
- {
- int mem = ++pParse.nMem;
- sqlite3VdbeAddOp1( v, OP_If, mem );
- testAddr = sqlite3VdbeAddOp2( v, OP_Integer, 1, mem );
- Debug.Assert( testAddr > 0 /* || pParse.db.mallocFailed != 0 */ );
- }
-#if !SQLITE_OMIT_EXPLAIN
- if ( pParse.explain == 2 )
- {
- string zMsg = sqlite3MPrintf(
- pParse.db, "EXECUTE %s%s SUBQUERY %d", testAddr != 0 ? string.Empty : "CORRELATED ",
- pExpr.op == TK_IN ? "LIST" : "SCALAR", pParse.iNextSelectId
- );
- sqlite3VdbeAddOp4( v, OP_Explain, pParse.iSelectId, 0, 0, zMsg, P4_DYNAMIC );
- }
-#endif
-
- switch ( pExpr.op )
- {
- case TK_IN:
- {
- char affinity; /* Affinity of the LHS of the IN */
- KeyInfo keyInfo; /* Keyinfo for the generated table */
- int addr; /* Address of OP_OpenEphemeral instruction */
- Expr pLeft = pExpr.pLeft; /* the LHS of the IN operator */
+ /*
+ ** Generate an OP_IsNull instruction that tests register iReg and jumps
+ ** to location iDest if the value in iReg is NULL. The value in iReg
+ ** was computed by pExpr. If we can look at pExpr at compile-time and
+ ** determine that it can never generate a NULL, then the OP_IsNull operation
+ ** can be omitted.
+ */
+ static void sqlite3ExprCodeIsNullJump(
+ Vdbe v, /* The VDBE under construction */
+ Expr pExpr, /* Only generate OP_IsNull if this expr can be NULL */
+ int iReg, /* Test the value in this register for NULL */
+ int iDest /* Jump here if the value is null */
+ ) {
+ if (sqlite3ExprCanBeNull(pExpr) != 0) {
+ sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
+ }
+ }
- if ( rMayHaveNull != 0 )
- {
- sqlite3VdbeAddOp2( v, OP_Null, 0, rMayHaveNull );
+ /*
+ ** Return TRUE if the given expression is a constant which would be
+ ** unchanged by OP_Affinity with the affinity given in the second
+ ** argument.
+ **
+ ** This routine is used to determine if the OP_Affinity operation
+ ** can be omitted. When in doubt return FALSE. A false negative
+ ** is harmless. A false positive, however, can result in the wrong
+ ** answer.
+ */
+ static int sqlite3ExprNeedsNoAffinityChange(Expr p, char aff) {
+ u8 op;
+ if (aff == SQLITE_AFF_NONE)
+ return 1;
+ while (p.op == TK_UPLUS || p.op == TK_UMINUS) {
+ p = p.pLeft;
+ }
+ op = p.op;
+ if (op == TK_REGISTER)
+ op = p.op2;
+ switch (op) {
+ case TK_INTEGER: {
+ return (aff == SQLITE_AFF_INTEGER || aff == SQLITE_AFF_NUMERIC) ? 1 : 0;
+ }
+ case TK_FLOAT: {
+ return (aff == SQLITE_AFF_REAL || aff == SQLITE_AFF_NUMERIC) ? 1 : 0;
+ }
+ case TK_STRING: {
+ return (aff == SQLITE_AFF_TEXT) ? 1 : 0;
+ }
+ case TK_BLOB: {
+ return 1;
+ }
+ case TK_COLUMN: {
+ Debug.Assert(p.iTable >= 0); /* p cannot be part of a CHECK constraint */
+ return (p.iColumn < 0
+ && (aff == SQLITE_AFF_INTEGER || aff == SQLITE_AFF_NUMERIC)) ? 1 : 0;
+ }
+ default: {
+ return 0;
+ }
}
+ }
- affinity = sqlite3ExprAffinity( pLeft );
+ /*
+ ** Return TRUE if the given string is a row-id column name.
+ */
+ static bool sqlite3IsRowid(string z) {
+ if (z.Equals("_ROWID_", StringComparison.OrdinalIgnoreCase))
+ return true;
+ if (z.Equals("ROWID", StringComparison.OrdinalIgnoreCase))
+ return true;
+ if (z.Equals("OID", StringComparison.OrdinalIgnoreCase))
+ return true;
+ return false;
+ }
- /* Whether this is an 'x IN(SELECT...)' or an 'x IN()'
- ** expression it is handled the same way. An ephemeral table is
- ** filled with single-field index keys representing the results
- ** from the SELECT or the .
- **
- ** If the 'x' expression is a column value, or the SELECT...
- ** statement returns a column value, then the affinity of that
- ** column is used to build the index keys. If both 'x' and the
- ** SELECT... statement are columns, then numeric affinity is used
- ** if either column has NUMERIC or INTEGER affinity. If neither
- ** 'x' nor the SELECT... statement are columns, then numeric affinity
- ** is used.
- */
- pExpr.iTable = pParse.nTab++;
- addr = sqlite3VdbeAddOp2( v, OP_OpenEphemeral, (int)pExpr.iTable, !isRowid );
- if ( rMayHaveNull == 0 )
- sqlite3VdbeChangeP5( v, BTREE_UNORDERED );
- keyInfo = new KeyInfo();// memset( &keyInfo, 0, sizeof(keyInfo ));
- keyInfo.nField = 1;
-
- if ( ExprHasProperty( pExpr, EP_xIsSelect ) )
- {
- /* Case 1: expr IN (SELECT ...)
- **
- ** Generate code to write the results of the select into the temporary
- ** table allocated and opened above.
- */
- SelectDest dest = new SelectDest();
- ExprList pEList;
-
- Debug.Assert( !isRowid );
- sqlite3SelectDestInit( dest, SRT_Set, pExpr.iTable );
- dest.affinity = (char)affinity;
- Debug.Assert( ( pExpr.iTable & 0x0000FFFF ) == pExpr.iTable );
- pExpr.x.pSelect.iLimit = 0;
- if ( sqlite3Select( pParse, pExpr.x.pSelect, ref dest ) != 0 )
- {
- return 0;
- }
- pEList = pExpr.x.pSelect.pEList;
- if ( ALWAYS( pEList != null ) && pEList.nExpr > 0 )
- {
- keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq( pParse, pExpr.pLeft,
- pEList.a[0].pExpr );
- }
+
+ /*
+ ** Return true if we are able to the IN operator optimization on a
+ ** query of the form
+ **
+ ** x IN (SELECT ...)
+ **
+ ** Where the SELECT... clause is as specified by the parameter to this
+ ** routine.
+ **
+ ** The Select object passed in has already been preprocessed and no
+ ** errors have been found.
+ */
+#if !SQLITE_OMIT_SUBQUERY
+ static int isCandidateForInOpt(Select p) {
+ SrcList pSrc;
+ ExprList pEList;
+ Table pTab;
+ if (p == null)
+ return 0; /* right-hand side of IN is SELECT */
+ if (p.pPrior != null)
+ return 0; /* Not a compound SELECT */
+ if ((p.selFlags & (SF_Distinct | SF_Aggregate)) != 0) {
+ testcase((p.selFlags & (SF_Distinct | SF_Aggregate)) == SF_Distinct);
+ testcase((p.selFlags & (SF_Distinct | SF_Aggregate)) == SF_Aggregate);
+ return 0; /* No DISTINCT keyword and no aggregate functions */
}
- else if ( ALWAYS( pExpr.x.pList != null ) )
- {
- /* Case 2: expr IN (exprlist)
- **
- ** For each expression, build an index key from the evaluation and
- ** store it in the temporary table. If is a column, then use
- ** that columns affinity when building index keys. If is not
- ** a column, use numeric affinity.
- */
- int i;
- ExprList pList = pExpr.x.pList;
- ExprList_item pItem;
- int r1, r2, r3;
-
- if ( affinity == '\0' )
- {
- affinity = SQLITE_AFF_NONE;
- }
- keyInfo.aColl[0] = sqlite3ExprCollSeq( pParse, pExpr.pLeft );
-
- /* Loop through each expression in . */
- r1 = sqlite3GetTempReg( pParse );
- r2 = sqlite3GetTempReg( pParse );
- sqlite3VdbeAddOp2( v, OP_Null, 0, r2 );
- for ( i = 0; i < pList.nExpr; i++ )
- {//, pItem++){
- pItem = pList.a[i];
- Expr pE2 = pItem.pExpr;
- int iValToIns = 0;
+ Debug.Assert(p.pGroupBy == null); /* Has no GROUP BY clause */
+ if (p.pLimit != null)
+ return 0; /* Has no LIMIT clause */
+ Debug.Assert(p.pOffset == null); /* No LIMIT means no OFFSET */
+
+ if (p.pWhere != null)
+ return 0; /* Has no WHERE clause */
+ pSrc = p.pSrc;
+ Debug.Assert(pSrc != null);
+ if (pSrc.nSrc != 1)
+ return 0; /* Single term in FROM clause */
+ if (pSrc.a[0].pSelect != null)
+ return 0; /* FROM is not a subquery or view */
+ pTab = pSrc.a[0].pTab;
+ if (NEVER(pTab == null))
+ return 0;
+ Debug.Assert(pTab.pSelect == null); /* FROM clause is not a view */
+ if (IsVirtual(pTab))
+ return 0; /* FROM clause not a virtual table */
+ pEList = p.pEList;
+ if (pEList.nExpr != 1)
+ return 0; /* One column in the result set */
+ if (pEList.a[0].pExpr.op != TK_COLUMN)
+ return 0; /* Result is a column */
+ return 1;
+ }
+#endif //* SQLITE_OMIT_SUBQUERY */
+
+ /*
+ ** This function is used by the implementation of the IN (...) operator.
+ ** It's job is to find or create a b-tree structure that may be used
+ ** either to test for membership of the (...) set or to iterate through
+ ** its members, skipping duplicates.
+ **
+ ** The index of the cursor opened on the b-tree (database table, database index
+ ** or ephermal table) is stored in pX->iTable before this function returns.
+ ** The returned value of this function indicates the b-tree type, as follows:
+ **
+ ** IN_INDEX_ROWID - The cursor was opened on a database table.
+ ** IN_INDEX_INDEX - The cursor was opened on a database index.
+ ** IN_INDEX_EPH - The cursor was opened on a specially created and
+ ** populated epheremal table.
+ **
+ ** An existing b-tree may only be used if the SELECT is of the simple
+ ** form:
+ **
+ ** SELECT FROM
+ **
+ ** If the prNotFound parameter is 0, then the b-tree will be used to iterate
+ ** through the set members, skipping any duplicates. In this case an
+ ** epheremal table must be used unless the selected is guaranteed
+ ** to be unique - either because it is an INTEGER PRIMARY KEY or it
+ ** has a UNIQUE constraint or UNIQUE index.
+ **
+ ** If the prNotFound parameter is not 0, then the b-tree will be used
+ ** for fast set membership tests. In this case an epheremal table must
+ ** be used unless is an INTEGER PRIMARY KEY or an index can
+ ** be found with as its left-most column.
+ **
+ ** When the b-tree is being used for membership tests, the calling function
+ ** needs to know whether or not the structure contains an SQL NULL
+ ** value in order to correctly evaluate expressions like "X IN (Y, Z)".
+ ** If there is any chance that the (...) might contain a NULL value at
+ ** runtime, then a register is allocated and the register number written
+ ** to *prNotFound. If there is no chance that the (...) contains a
+ ** NULL value, then *prNotFound is left unchanged.
+ **
+ ** If a register is allocated and its location stored in *prNotFound, then
+ ** its initial value is NULL. If the (...) does not remain constant
+ ** for the duration of the query (i.e. the SELECT within the (...)
+ ** is a correlated subquery) then the value of the allocated register is
+ ** reset to NULL each time the subquery is rerun. This allows the
+ ** caller to use vdbe code equivalent to the following:
+ **
+ ** if( register==NULL ){
+ ** has_null =
+ ** register = 1
+ ** }
+ **
+ ** in order to avoid running the
+ ** test more often than is necessary.
+ */
+#if !SQLITE_OMIT_SUBQUERY
+ static int sqlite3FindInIndex(Parse pParse, Expr pX, ref int prNotFound) {
+ Select p; /* SELECT to the right of IN operator */
+ int eType = 0; /* Type of RHS table. IN_INDEX_* */
+ int iTab = pParse.nTab++; /* Cursor of the RHS table */
+ bool mustBeUnique = (prNotFound != 0); /* True if RHS must be unique */
- /* If the expression is not constant then we will need to
- ** disable the test that was generated above that makes sure
- ** this code only executes once. Because for a non-constant
- ** expression we need to rerun this code each time.
+ Debug.Assert(pX.op == TK_IN);
+
+ /* Check to see if an existing table or index can be used to
+ ** satisfy the query. This is preferable to generating a new
+ ** ephemeral table.
+ */
+ p = (ExprHasProperty(pX, EP_xIsSelect) ? pX.x.pSelect : null);
+ if (ALWAYS(pParse.nErr == 0) && isCandidateForInOpt(p) != 0) {
+ sqlite3 db = pParse.db; /* Database connection */
+ Expr pExpr = p.pEList.a[0].pExpr; /* Expression */
+ int iCol = pExpr.iColumn; /* Index of column */
+ Vdbe v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
+ Table pTab = p.pSrc.a[0].pTab; /* Table
. */
+ int iDb; /* Database idx for pTab */
+
+ /* Code an OP_VerifyCookie and OP_TableLock for
. */
+ iDb = sqlite3SchemaToIndex(db, pTab.pSchema);
+ sqlite3CodeVerifySchema(pParse, iDb);
+ sqlite3TableLock(pParse, iDb, pTab.tnum, 0, pTab.zName);
+
+ /* This function is only called from two places. In both cases the vdbe
+ ** has already been allocated. So assume sqlite3GetVdbe() is always
+ ** successful here.
*/
- if ( testAddr != 0 && sqlite3ExprIsConstant( pE2 ) == 0 )
- {
- sqlite3VdbeChangeToNoop( v, testAddr - 1, 2 );
- testAddr = 0;
- }
+ Debug.Assert(v != null);
+ if (iCol < 0) {
+ int iMem = ++pParse.nMem;
+ int iAddr;
+
+ iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
+
+ sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
+ eType = IN_INDEX_ROWID;
+
+ sqlite3VdbeJumpHere(v, iAddr);
+ } else {
+ Index pIdx; /* Iterator variable */
+ /* The collation sequence used by the comparison. If an index is to
+ ** be used in place of a temp.table, it must be ordered according
+ ** to this collation sequence. */
+ CollSeq pReq = sqlite3BinaryCompareCollSeq(pParse, pX.pLeft, pExpr);
+
+ /* Check that the affinity that will be used to perform the
+ ** comparison is the same as the affinity of the column. If
+ ** it is not, it is not possible to use any index.
+ */
+ char aff = comparisonAffinity(pX);
+ bool affinity_ok = (pTab.aCol[iCol].affinity == aff || aff == SQLITE_AFF_NONE);
+
+ for (pIdx = pTab.pIndex; pIdx != null && eType == 0 && affinity_ok; pIdx = pIdx.pNext) {
+ if ((pIdx.aiColumn[0] == iCol)
+ && (sqlite3FindCollSeq(db, ENC(db), pIdx.azColl[0], 0) == pReq)
+ && (mustBeUnique == false || (pIdx.nColumn == 1 && pIdx.onError != OE_None))
+ ) {
+ int iMem = ++pParse.nMem;
+ int iAddr;
+ KeyInfo pKey;
+
+ pKey = sqlite3IndexKeyinfo(pParse, pIdx);
+
+ iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
+
+ sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx.tnum, iDb,
+ pKey, P4_KEYINFO_HANDOFF);
+#if SQLITE_DEBUG
+ VdbeComment(v, "%s", pIdx.zName);
+#endif
+ eType = IN_INDEX_INDEX;
- /* Evaluate the expression and insert it into the temp table */
- if ( isRowid && sqlite3ExprIsInteger( pE2, ref iValToIns ) != 0 )
- {
- sqlite3VdbeAddOp3( v, OP_InsertInt, pExpr.iTable, r2, iValToIns );
+ sqlite3VdbeJumpHere(v, iAddr);
+ if ( //prNotFound != null && -- always exists under C#
+ pTab.aCol[iCol].notNull == 0) {
+ prNotFound = ++pParse.nMem;
+ }
+ }
+ }
}
- else
+ }
+
+ if (eType == 0) {
+ /* Could not found an existing table or index to use as the RHS b-tree.
+ ** We will have to generate an ephemeral table to do the job.
+ */
+ double savedNQueryLoop = pParse.nQueryLoop;
+ int rMayHaveNull = 0;
+ eType = IN_INDEX_EPH;
+ if (prNotFound != -1) // Klude to show prNotFound not available
{
- r3 = sqlite3ExprCodeTarget( pParse, pE2, r1 );
- if ( isRowid )
- {
- sqlite3VdbeAddOp2( v, OP_MustBeInt, r3,
- sqlite3VdbeCurrentAddr( v ) + 2 );
- sqlite3VdbeAddOp3( v, OP_Insert, pExpr.iTable, r2, r3 );
- }
- else
- {
- sqlite3VdbeAddOp4( v, OP_MakeRecord, r3, 1, r2, affinity, 1 );
- sqlite3ExprCacheAffinityChange( pParse, r3, 1 );
- sqlite3VdbeAddOp2( v, OP_IdxInsert, pExpr.iTable, r2 );
- }
+ prNotFound = rMayHaveNull = ++pParse.nMem;
+ } else {
+ testcase(pParse.nQueryLoop > (double)1);
+ pParse.nQueryLoop = (double)1;
+ if (pX.pLeft.iColumn < 0 && !ExprHasAnyProperty(pX, EP_xIsSelect)) {
+ eType = IN_INDEX_ROWID;
+ }
}
- }
- sqlite3ReleaseTempReg( pParse, r1 );
- sqlite3ReleaseTempReg( pParse, r2 );
+ sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType == IN_INDEX_ROWID);
+ pParse.nQueryLoop = savedNQueryLoop;
+ } else {
+ pX.iTable = iTab;
}
- if ( !isRowid )
- {
- sqlite3VdbeChangeP4( v, addr, keyInfo, P4_KEYINFO );
- }
- break;
- }
+ return eType;
+ }
+#endif
- case TK_EXISTS:
- case TK_SELECT:
- default:
- {
- /* If this has to be a scalar SELECT. Generate code to put the
- ** value of this select in a memory cell and record the number
- ** of the memory cell in iColumn. If this is an EXISTS, write
- ** an integer 0 (not exists) or 1 (exists) into a memory cell
- ** and record that memory cell in iColumn.
+ /*
+ ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
+ ** or IN operators. Examples:
+ **
+ ** (SELECT a FROM b) -- subquery
+ ** EXISTS (SELECT a FROM b) -- EXISTS subquery
+ ** x IN (4,5,11) -- IN operator with list on right-hand side
+ ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
+ **
+ ** The pExpr parameter describes the expression that contains the IN
+ ** operator or subquery.
+ **
+ ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
+ ** to be of the form " IN (?, ?, ?)", where is a reference
+ ** to some integer key column of a table B-Tree. In this case, use an
+ ** intkey B-Tree to store the set of IN(...) values instead of the usual
+ ** (slower) variable length keys B-Tree.
+ **
+ ** If rMayHaveNull is non-zero, that means that the operation is an IN
+ ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
+ ** Furthermore, the IN is in a WHERE clause and that we really want
+ ** to iterate over the RHS of the IN operator in order to quickly locate
+ ** all corresponding LHS elements. All this routine does is initialize
+ ** the register given by rMayHaveNull to NULL. Calling routines will take
+ ** care of changing this register value to non-NULL if the RHS is NULL-free.
+ **
+ ** If rMayHaveNull is zero, that means that the subquery is being used
+ ** for membership testing only. There is no need to initialize any
+ ** registers to indicate the presense or absence of NULLs on the RHS.
+ **
+ ** For a SELECT or EXISTS operator, return the register that holds the
+ ** result. For IN operators or if an error occurs, the return value is 0.
+ */
+#if !SQLITE_OMIT_SUBQUERY
+ static int sqlite3CodeSubselect(
+ Parse pParse, /* Parsing context */
+ Expr pExpr, /* The IN, SELECT, or EXISTS operator */
+ int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
+ bool isRowid /* If true, LHS of IN operator is a rowid */
+ ) {
+ int testAddr = 0; /* One-time test address */
+ int rReg = 0; /* Register storing resulting */
+ Vdbe v = sqlite3GetVdbe(pParse);
+ if (NEVER(v == null))
+ return 0;
+ sqlite3ExprCachePush(pParse);
+
+ /* This code must be run in its entirety every time it is encountered
+ ** if any of the following is true:
+ **
+ ** * The right-hand side is a correlated subquery
+ ** * The right-hand side is an expression list containing variables
+ ** * We are inside a trigger
+ **
+ ** If all of the above are false, then we can run this code just once
+ ** save the results, and reuse the same result on subsequent invocations.
*/
- Select pSel; /* SELECT statement to encode */
- SelectDest dest = new SelectDest(); /* How to deal with SELECt result */
+ if (!ExprHasAnyProperty(pExpr, EP_VarSelect) && null == pParse.pTriggerTab) {
+ int mem = ++pParse.nMem;
+ sqlite3VdbeAddOp1(v, OP_If, mem);
+ testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
+ Debug.Assert(testAddr > 0 /* || pParse.db.mallocFailed != 0 */ );
+ }
+
+#if !SQLITE_OMIT_EXPLAIN
+ if (pParse.explain == 2) {
+ string zMsg = sqlite3MPrintf(
+ pParse.db, "EXECUTE %s%s SUBQUERY %d", testAddr != 0 ? string.Empty : "CORRELATED ",
+ pExpr.op == TK_IN ? "LIST" : "SCALAR", pParse.iNextSelectId
+ );
+ sqlite3VdbeAddOp4(v, OP_Explain, pParse.iSelectId, 0, 0, zMsg, P4_DYNAMIC);
+ }
+#endif
- testcase( pExpr.op == TK_EXISTS );
- testcase( pExpr.op == TK_SELECT );
- Debug.Assert( pExpr.op == TK_EXISTS || pExpr.op == TK_SELECT );
+ switch (pExpr.op) {
+ case TK_IN: {
+ char affinity; /* Affinity of the LHS of the IN */
+ KeyInfo keyInfo; /* Keyinfo for the generated table */
+ int addr; /* Address of OP_OpenEphemeral instruction */
+ Expr pLeft = pExpr.pLeft; /* the LHS of the IN operator */
- Debug.Assert( ExprHasProperty( pExpr, EP_xIsSelect ) );
- pSel = pExpr.x.pSelect;
- sqlite3SelectDestInit( dest, 0, ++pParse.nMem );
- if ( pExpr.op == TK_SELECT )
- {
- dest.eDest = SRT_Mem;
- sqlite3VdbeAddOp2( v, OP_Null, 0, dest.iParm );
+ if (rMayHaveNull != 0) {
+ sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
+ }
+
+ affinity = sqlite3ExprAffinity(pLeft);
+
+ /* Whether this is an 'x IN(SELECT...)' or an 'x IN()'
+ ** expression it is handled the same way. An ephemeral table is
+ ** filled with single-field index keys representing the results
+ ** from the SELECT or the .
+ **
+ ** If the 'x' expression is a column value, or the SELECT...
+ ** statement returns a column value, then the affinity of that
+ ** column is used to build the index keys. If both 'x' and the
+ ** SELECT... statement are columns, then numeric affinity is used
+ ** if either column has NUMERIC or INTEGER affinity. If neither
+ ** 'x' nor the SELECT... statement are columns, then numeric affinity
+ ** is used.
+ */
+ pExpr.iTable = pParse.nTab++;
+ addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, (int)pExpr.iTable, !isRowid);
+ if (rMayHaveNull == 0)
+ sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
+ keyInfo = new KeyInfo();// memset( &keyInfo, 0, sizeof(keyInfo ));
+ keyInfo.nField = 1;
+
+ if (ExprHasProperty(pExpr, EP_xIsSelect)) {
+ /* Case 1: expr IN (SELECT ...)
+ **
+ ** Generate code to write the results of the select into the temporary
+ ** table allocated and opened above.
+ */
+ SelectDest dest = new SelectDest();
+ ExprList pEList;
+
+ Debug.Assert(!isRowid);
+ sqlite3SelectDestInit(dest, SRT_Set, pExpr.iTable);
+ dest.affinity = (char)affinity;
+ Debug.Assert((pExpr.iTable & 0x0000FFFF) == pExpr.iTable);
+ pExpr.x.pSelect.iLimit = 0;
+ if (sqlite3Select(pParse, pExpr.x.pSelect, ref dest) != 0) {
+ return 0;
+ }
+ pEList = pExpr.x.pSelect.pEList;
+ if (ALWAYS(pEList != null) && pEList.nExpr > 0) {
+ keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr.pLeft,
+ pEList.a[0].pExpr);
+ }
+ } else if (ALWAYS(pExpr.x.pList != null)) {
+ /* Case 2: expr IN (exprlist)
+ **
+ ** For each expression, build an index key from the evaluation and
+ ** store it in the temporary table. If is a column, then use
+ ** that columns affinity when building index keys. If is not
+ ** a column, use numeric affinity.
+ */
+ int i;
+ ExprList pList = pExpr.x.pList;
+ ExprList_item pItem;
+ int r1, r2, r3;
+
+ if (affinity == '\0') {
+ affinity = SQLITE_AFF_NONE;
+ }
+ keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr.pLeft);
+
+ /* Loop through each expression in . */
+ r1 = sqlite3GetTempReg(pParse);
+ r2 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
+ for (i = 0; i < pList.nExpr; i++) {//, pItem++){
+ pItem = pList.a[i];
+ Expr pE2 = pItem.pExpr;
+ int iValToIns = 0;
+
+ /* If the expression is not constant then we will need to
+ ** disable the test that was generated above that makes sure
+ ** this code only executes once. Because for a non-constant
+ ** expression we need to rerun this code each time.
+ */
+ if (testAddr != 0 && sqlite3ExprIsConstant(pE2) == 0) {
+ sqlite3VdbeChangeToNoop(v, testAddr - 1, 2);
+ testAddr = 0;
+ }
+
+ /* Evaluate the expression and insert it into the temp table */
+ if (isRowid && sqlite3ExprIsInteger(pE2, ref iValToIns) != 0) {
+ sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr.iTable, r2, iValToIns);
+ } else {
+ r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
+ if (isRowid) {
+ sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
+ sqlite3VdbeCurrentAddr(v) + 2);
+ sqlite3VdbeAddOp3(v, OP_Insert, pExpr.iTable, r2, r3);
+ } else {
+ sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, affinity, 1);
+ sqlite3ExprCacheAffinityChange(pParse, r3, 1);
+ sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr.iTable, r2);
+ }
+ }
+ }
+ sqlite3ReleaseTempReg(pParse, r1);
+ sqlite3ReleaseTempReg(pParse, r2);
+ }
+ if (!isRowid) {
+ sqlite3VdbeChangeP4(v, addr, keyInfo, P4_KEYINFO);
+ }
+ break;
+ }
+
+ case TK_EXISTS:
+ case TK_SELECT:
+ default: {
+ /* If this has to be a scalar SELECT. Generate code to put the
+ ** value of this select in a memory cell and record the number
+ ** of the memory cell in iColumn. If this is an EXISTS, write
+ ** an integer 0 (not exists) or 1 (exists) into a memory cell
+ ** and record that memory cell in iColumn.
+ */
+ Select pSel; /* SELECT statement to encode */
+ SelectDest dest = new SelectDest(); /* How to deal with SELECt result */
+
+ testcase(pExpr.op == TK_EXISTS);
+ testcase(pExpr.op == TK_SELECT);
+ Debug.Assert(pExpr.op == TK_EXISTS || pExpr.op == TK_SELECT);
+
+ Debug.Assert(ExprHasProperty(pExpr, EP_xIsSelect));
+ pSel = pExpr.x.pSelect;
+ sqlite3SelectDestInit(dest, 0, ++pParse.nMem);
+ if (pExpr.op == TK_SELECT) {
+ dest.eDest = SRT_Mem;
+ sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
#if SQLITE_DEBUG
- VdbeComment( v, "Init subquery result" );
+ VdbeComment(v, "Init subquery result");
#endif
- }
- else
- {
- dest.eDest = SRT_Exists;
- sqlite3VdbeAddOp2( v, OP_Integer, 0, dest.iParm );
+ } else {
+ dest.eDest = SRT_Exists;
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
#if SQLITE_DEBUG
- VdbeComment( v, "Init EXISTS result" );
+ VdbeComment(v, "Init EXISTS result");
#endif
+ }
+ sqlite3ExprDelete(pParse.db, ref pSel.pLimit);
+ pSel.pLimit = sqlite3PExpr(pParse, TK_INTEGER, null, null, sqlite3IntTokens[1]);
+ pSel.iLimit = 0;
+ if (sqlite3Select(pParse, pSel, ref dest) != 0) {
+ return 0;
+ }
+ rReg = dest.iParm;
+ ExprSetIrreducible(pExpr);
+ break;
+ }
}
- sqlite3ExprDelete( pParse.db, ref pSel.pLimit );
- pSel.pLimit = sqlite3PExpr( pParse, TK_INTEGER, null, null, sqlite3IntTokens[1] );
- pSel.iLimit = 0;
- if ( sqlite3Select( pParse, pSel, ref dest ) != 0 )
- {
- return 0;
- }
- rReg = dest.iParm;
- ExprSetIrreducible( pExpr );
- break;
- }
- }
- if ( testAddr != 0 )
- {
- sqlite3VdbeJumpHere( v, testAddr - 1 );
- }
- sqlite3ExprCachePop( pParse, 1 );
+ if (testAddr != 0) {
+ sqlite3VdbeJumpHere(v, testAddr - 1);
+ }
+ sqlite3ExprCachePop(pParse, 1);
- return rReg;
- }
+ return rReg;
+ }
#endif // * SQLITE_OMIT_SUBQUERY */
#if !SQLITE_OMIT_SUBQUERY
- /*
-** Generate code for an IN expression.
-**
-** x IN (SELECT ...)
-** x IN (value, value, ...)
-**
-** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
-** is an array of zero or more values. The expression is true if the LHS is
-** contained within the RHS. The value of the expression is unknown (NULL)
-** if the LHS is NULL or if the LHS is not contained within the RHS and the
-** RHS contains one or more NULL values.
-**
-** This routine generates code will jump to destIfFalse if the LHS is not
-** contained within the RHS. If due to NULLs we cannot determine if the LHS
-** is contained in the RHS then jump to destIfNull. If the LHS is contained
-** within the RHS then fall through.
-*/
- static void sqlite3ExprCodeIN(
- Parse pParse, /* Parsing and code generating context */
- Expr pExpr, /* The IN expression */
- int destIfFalse, /* Jump here if LHS is not contained in the RHS */
- int destIfNull /* Jump here if the results are unknown due to NULLs */
- )
- {
- int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
- char affinity; /* Comparison affinity to use */
- int eType; /* Type of the RHS */
- int r1; /* Temporary use register */
- Vdbe v; /* Statement under construction */
-
- /* Compute the RHS. After this step, the table with cursor
- ** pExpr.iTable will contains the values that make up the RHS.
- */
- v = pParse.pVdbe;
- Debug.Assert( v != null ); /* OOM detected prior to this routine */
- VdbeNoopComment( v, "begin IN expr" );
- eType = sqlite3FindInIndex( pParse, pExpr, ref rRhsHasNull );
-
- /* Figure out the affinity to use to create a key from the results
- ** of the expression. affinityStr stores a static string suitable for
- ** P4 of OP_MakeRecord.
- */
- affinity = comparisonAffinity( pExpr );
-
- /* Code the LHS, the from " IN (...)".
- */
- sqlite3ExprCachePush( pParse );
- r1 = sqlite3GetTempReg( pParse );
- sqlite3ExprCode( pParse, pExpr.pLeft, r1 );
-
- /* If the LHS is NULL, then the result is either false or NULL depending
- ** on whether the RHS is empty or not, respectively.
- */
- if ( destIfNull == destIfFalse )
- {
- /* Shortcut for the common case where the false and NULL outcomes are
- ** the same. */
- sqlite3VdbeAddOp2( v, OP_IsNull, r1, destIfNull );
- }
- else
- {
- int addr1 = sqlite3VdbeAddOp1( v, OP_NotNull, r1 );
- sqlite3VdbeAddOp2( v, OP_Rewind, pExpr.iTable, destIfFalse );
- sqlite3VdbeAddOp2( v, OP_Goto, 0, destIfNull );
- sqlite3VdbeJumpHere( v, addr1 );
- }
-
- if ( eType == IN_INDEX_ROWID )
- {
- /* In this case, the RHS is the ROWID of table b-tree
- */
- sqlite3VdbeAddOp2( v, OP_MustBeInt, r1, destIfFalse );
- sqlite3VdbeAddOp3( v, OP_NotExists, pExpr.iTable, destIfFalse, r1 );
- }
- else
- {
- /* In this case, the RHS is an index b-tree.
- */
- sqlite3VdbeAddOp4( v, OP_Affinity, r1, 1, 0, affinity, 1 );
+ /*
+ ** Generate code for an IN expression.
+ **
+ ** x IN (SELECT ...)
+ ** x IN (value, value, ...)
+ **
+ ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
+ ** is an array of zero or more values. The expression is true if the LHS is
+ ** contained within the RHS. The value of the expression is unknown (NULL)
+ ** if the LHS is NULL or if the LHS is not contained within the RHS and the
+ ** RHS contains one or more NULL values.
+ **
+ ** This routine generates code will jump to destIfFalse if the LHS is not
+ ** contained within the RHS. If due to NULLs we cannot determine if the LHS
+ ** is contained in the RHS then jump to destIfNull. If the LHS is contained
+ ** within the RHS then fall through.
+ */
+ static void sqlite3ExprCodeIN(
+ Parse pParse, /* Parsing and code generating context */
+ Expr pExpr, /* The IN expression */
+ int destIfFalse, /* Jump here if LHS is not contained in the RHS */
+ int destIfNull /* Jump here if the results are unknown due to NULLs */
+ ) {
+ int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
+ char affinity; /* Comparison affinity to use */
+ int eType; /* Type of the RHS */
+ int r1; /* Temporary use register */
+ Vdbe v; /* Statement under construction */
+
+ /* Compute the RHS. After this step, the table with cursor
+ ** pExpr.iTable will contains the values that make up the RHS.
+ */
+ v = pParse.pVdbe;
+ Debug.Assert(v != null); /* OOM detected prior to this routine */
+ VdbeNoopComment(v, "begin IN expr");
+ eType = sqlite3FindInIndex(pParse, pExpr, ref rRhsHasNull);
+
+ /* Figure out the affinity to use to create a key from the results
+ ** of the expression. affinityStr stores a static string suitable for
+ ** P4 of OP_MakeRecord.
+ */
+ affinity = comparisonAffinity(pExpr);
- /* If the set membership test fails, then the result of the
- ** "x IN (...)" expression must be either 0 or NULL. If the set
- ** contains no NULL values, then the result is 0. If the set
- ** contains one or more NULL values, then the result of the
- ** expression is also NULL.
- */
- if ( rRhsHasNull == 0 || destIfFalse == destIfNull )
- {
- /* This branch runs if it is known at compile time that the RHS
- ** cannot contain NULL values. This happens as the result
- ** of a "NOT NULL" constraint in the database schema.
- **
- ** Also run this branch if NULL is equivalent to FALSE
- ** for this particular IN operator.
- */
- sqlite3VdbeAddOp4Int( v, OP_NotFound, pExpr.iTable, destIfFalse, r1, 1 );
+ /* Code the LHS, the from " IN (...)".
+ */
+ sqlite3ExprCachePush(pParse);
+ r1 = sqlite3GetTempReg(pParse);
+ sqlite3ExprCode(pParse, pExpr.pLeft, r1);
+ /* If the LHS is NULL, then the result is either false or NULL depending
+ ** on whether the RHS is empty or not, respectively.
+ */
+ if (destIfNull == destIfFalse) {
+ /* Shortcut for the common case where the false and NULL outcomes are
+ ** the same. */
+ sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
+ } else {
+ int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
+ sqlite3VdbeAddOp2(v, OP_Rewind, pExpr.iTable, destIfFalse);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
+ sqlite3VdbeJumpHere(v, addr1);
+ }
+
+ if (eType == IN_INDEX_ROWID) {
+ /* In this case, the RHS is the ROWID of table b-tree
+ */
+ sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
+ sqlite3VdbeAddOp3(v, OP_NotExists, pExpr.iTable, destIfFalse, r1);
+ } else {
+ /* In this case, the RHS is an index b-tree.
+ */
+ sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, affinity, 1);
+
+ /* If the set membership test fails, then the result of the
+ ** "x IN (...)" expression must be either 0 or NULL. If the set
+ ** contains no NULL values, then the result is 0. If the set
+ ** contains one or more NULL values, then the result of the
+ ** expression is also NULL.
+ */
+ if (rRhsHasNull == 0 || destIfFalse == destIfNull) {
+ /* This branch runs if it is known at compile time that the RHS
+ ** cannot contain NULL values. This happens as the result
+ ** of a "NOT NULL" constraint in the database schema.
+ **
+ ** Also run this branch if NULL is equivalent to FALSE
+ ** for this particular IN operator.
+ */
+ sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr.iTable, destIfFalse, r1, 1);
+
+ } else {
+ /* In this branch, the RHS of the IN might contain a NULL and
+ ** the presence of a NULL on the RHS makes a difference in the
+ ** outcome.
+ */
+ int j1, j2, j3;
+
+ /* First check to see if the LHS is contained in the RHS. If so,
+ ** then the presence of NULLs in the RHS does not matter, so jump
+ ** over all of the code that follows.
+ */
+ j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr.iTable, 0, r1, 1);
+
+ /* Here we begin generating code that runs if the LHS is not
+ ** contained within the RHS. Generate additional code that
+ ** tests the RHS for NULLs. If the RHS contains a NULL then
+ ** jump to destIfNull. If there are no NULLs in the RHS then
+ ** jump to destIfFalse.
+ */
+ j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
+ j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr.iTable, 0, rRhsHasNull, 1);
+ sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
+ sqlite3VdbeJumpHere(v, j3);
+ sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
+ sqlite3VdbeJumpHere(v, j2);
+
+ /* Jump to the appropriate target depending on whether or not
+ ** the RHS contains a NULL
+ */
+ sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
+
+ /* The OP_Found at the top of this branch jumps here when true,
+ ** causing the overall IN expression evaluation to fall through.
+ */
+ sqlite3VdbeJumpHere(v, j1);
+ }
+ }
+ sqlite3ReleaseTempReg(pParse, r1);
+ sqlite3ExprCachePop(pParse, 1);
+ VdbeComment(v, "end IN expr");
}
- else
- {
- /* In this branch, the RHS of the IN might contain a NULL and
- ** the presence of a NULL on the RHS makes a difference in the
- ** outcome.
- */
- int j1, j2, j3;
-
- /* First check to see if the LHS is contained in the RHS. If so,
- ** then the presence of NULLs in the RHS does not matter, so jump
- ** over all of the code that follows.
- */
- j1 = sqlite3VdbeAddOp4Int( v, OP_Found, pExpr.iTable, 0, r1, 1 );
-
- /* Here we begin generating code that runs if the LHS is not
- ** contained within the RHS. Generate additional code that
- ** tests the RHS for NULLs. If the RHS contains a NULL then
- ** jump to destIfNull. If there are no NULLs in the RHS then
- ** jump to destIfFalse.
- */
- j2 = sqlite3VdbeAddOp1( v, OP_NotNull, rRhsHasNull );
- j3 = sqlite3VdbeAddOp4Int( v, OP_Found, pExpr.iTable, 0, rRhsHasNull, 1 );
- sqlite3VdbeAddOp2( v, OP_Integer, -1, rRhsHasNull );
- sqlite3VdbeJumpHere( v, j3 );
- sqlite3VdbeAddOp2( v, OP_AddImm, rRhsHasNull, 1 );
- sqlite3VdbeJumpHere( v, j2 );
-
- /* Jump to the appropriate target depending on whether or not
- ** the RHS contains a NULL
- */
- sqlite3VdbeAddOp2( v, OP_If, rRhsHasNull, destIfNull );
- sqlite3VdbeAddOp2( v, OP_Goto, 0, destIfFalse );
-
- /* The OP_Found at the top of this branch jumps here when true,
- ** causing the overall IN expression evaluation to fall through.
- */
- sqlite3VdbeJumpHere( v, j1 );
- }
- }
- sqlite3ReleaseTempReg( pParse, r1 );
- sqlite3ExprCachePop( pParse, 1 );
- VdbeComment( v, "end IN expr" );
- }
#endif //* SQLITE_OMIT_SUBQUERY */
- /*
-** Duplicate an 8-byte value
-*/
- //static char *dup8bytes(Vdbe v, string in){
- // char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
- // if( out ){
- // memcpy(out, in, 8);
- // }
- // return out;
- //}
+ /*
+ ** Duplicate an 8-byte value
+ */
+ //static char *dup8bytes(Vdbe v, string in){
+ // char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
+ // if( out ){
+ // memcpy(out, in, 8);
+ // }
+ // return out;
+ //}
#if !SQLITE_OMIT_FLOATING_POINT
- /*
-** Generate an instruction that will put the floating point
-** value described by z[0..n-1] into register iMem.
-**
-** The z[] string will probably not be zero-terminated. But the
-** z[n] character is guaranteed to be something that does not look
-** like the continuation of the number.
-*/
- static void codeReal( Vdbe v, string z, bool negateFlag, int iMem )
- {
- if ( ALWAYS( !string.IsNullOrEmpty( z ) ) )
- {
- double value = 0;
- //string zV;
- sqlite3AtoF( z, ref value, sqlite3Strlen30( z ), SQLITE_UTF8 );
- Debug.Assert( !sqlite3IsNaN( value ) ); /* The new AtoF never returns NaN */
- if ( negateFlag )
- value = -value;
- //zV = dup8bytes(v, value);
- sqlite3VdbeAddOp4( v, OP_Real, 0, iMem, 0, value, P4_REAL );
- }
- }
+ /*
+ ** Generate an instruction that will put the floating point
+ ** value described by z[0..n-1] into register iMem.
+ **
+ ** The z[] string will probably not be zero-terminated. But the
+ ** z[n] character is guaranteed to be something that does not look
+ ** like the continuation of the number.
+ */
+ static void codeReal(Vdbe v, string z, bool negateFlag, int iMem) {
+ if (ALWAYS(!string.IsNullOrEmpty(z))) {
+ double value = 0;
+ //string zV;
+ sqlite3AtoF(z, ref value, sqlite3Strlen30(z), SQLITE_UTF8);
+ Debug.Assert(!sqlite3IsNaN(value)); /* The new AtoF never returns NaN */
+ if (negateFlag)
+ value = -value;
+ //zV = dup8bytes(v, value);
+ sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, value, P4_REAL);
+ }
+ }
#endif
- /*
- ** Generate an instruction that will put the integer describe by
- ** text z[0..n-1] into register iMem.
- **
- ** Expr.u.zToken is always UTF8 and zero-terminated.
- */
- static void codeInteger( Parse pParse, Expr pExpr, bool negFlag, int iMem )
- {
- Vdbe v = pParse.pVdbe;
- if ( ( pExpr.flags & EP_IntValue ) != 0 )
- {
- int i = pExpr.u.iValue;
- Debug.Assert( i >= 0 );
- if ( negFlag )
- i = -i;
- sqlite3VdbeAddOp2( v, OP_Integer, i, iMem );
- }
- else
- {
- int c;
- i64 value = 0;
- string z = pExpr.u.zToken;
- Debug.Assert( !string.IsNullOrEmpty( z ) );
- c = sqlite3Atoi64( z, ref value, sqlite3Strlen30( z ), SQLITE_UTF8 );
- if ( c == 0 || ( c == 2 && negFlag ) )
- {
- //char* zV;
- if ( negFlag )
- {
- value = c == 2 ? SMALLEST_INT64 : -value;
- }
- sqlite3VdbeAddOp4( v, OP_Int64, 0, iMem, 0, value, P4_INT64 );
- }
- else
- {
+ /*
+ ** Generate an instruction that will put the integer describe by
+ ** text z[0..n-1] into register iMem.
+ **
+ ** Expr.u.zToken is always UTF8 and zero-terminated.
+ */
+ static void codeInteger(Parse pParse, Expr pExpr, bool negFlag, int iMem) {
+ Vdbe v = pParse.pVdbe;
+ if ((pExpr.flags & EP_IntValue) != 0) {
+ int i = pExpr.u.iValue;
+ Debug.Assert(i >= 0);
+ if (negFlag)
+ i = -i;
+ sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
+ } else {
+ int c;
+ i64 value = 0;
+ string z = pExpr.u.zToken;
+ Debug.Assert(!string.IsNullOrEmpty(z));
+ c = sqlite3Atoi64(z, ref value, sqlite3Strlen30(z), SQLITE_UTF8);
+ if (c == 0 || (c == 2 && negFlag)) {
+ //char* zV;
+ if (negFlag) {
+ value = c == 2 ? SMALLEST_INT64 : -value;
+ }
+ sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, value, P4_INT64);
+ } else {
#if SQLITE_OMIT_FLOATING_POINT
sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : string.Empty, z);
#else
- codeReal( v, z, negFlag, iMem );
+ codeReal(v, z, negFlag, iMem);
#endif
+ }
+ }
}
- }
- }
- /*
- ** Clear a cache entry.
- */
- static void cacheEntryClear( Parse pParse, yColCache p )
- {
- if ( p.tempReg != 0 )
- {
- if ( pParse.nTempReg < ArraySize( pParse.aTempReg ) )
- {
- pParse.aTempReg[pParse.nTempReg++] = p.iReg;
+ /*
+ ** Clear a cache entry.
+ */
+ static void cacheEntryClear(Parse pParse, yColCache p) {
+ if (p.tempReg != 0) {
+ if (pParse.nTempReg < ArraySize(pParse.aTempReg)) {
+ pParse.aTempReg[pParse.nTempReg++] = p.iReg;
+ }
+ p.tempReg = 0;
+ }
}
- p.tempReg = 0;
- }
- }
- /*
- ** Record in the column cache that a particular column from a
- ** particular table is stored in a particular register.
- */
- static void sqlite3ExprCacheStore( Parse pParse, int iTab, int iCol, int iReg )
- {
- int i;
- int minLru;
- int idxLru;
- yColCache p = new yColCache();
-
- Debug.Assert( iReg > 0 ); /* Register numbers are always positive */
- Debug.Assert( iCol >= -1 && iCol < 32768 ); /* Finite column numbers */
-
- /* The SQLITE_ColumnCache flag disables the column cache. This is used
- ** for testing only - to verify that SQLite always gets the same answer
- ** with and without the column cache.
- */
- if ( ( pParse.db.flags & SQLITE_ColumnCache ) != 0 )
- return;
-
- /* First replace any existing entry.
- **
- ** Actually, the way the column cache is currently used, we are guaranteed
- ** that the object will never already be in cache. Verify this guarantee.
- */
+ /*
+ ** Record in the column cache that a particular column from a
+ ** particular table is stored in a particular register.
+ */
+ static void sqlite3ExprCacheStore(Parse pParse, int iTab, int iCol, int iReg) {
+ int i;
+ int minLru;
+ int idxLru;
+ yColCache p = new yColCache();
+
+ Debug.Assert(iReg > 0); /* Register numbers are always positive */
+ Debug.Assert(iCol >= -1 && iCol < 32768); /* Finite column numbers */
+
+ /* The SQLITE_ColumnCache flag disables the column cache. This is used
+ ** for testing only - to verify that SQLite always gets the same answer
+ ** with and without the column cache.
+ */
+ if ((pParse.db.flags & SQLITE_ColumnCache) != 0)
+ return;
+
+ /* First replace any existing entry.
+ **
+ ** Actually, the way the column cache is currently used, we are guaranteed
+ ** that the object will never already be in cache. Verify this guarantee.
+ */
#if !NDEBUG
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++)
- {
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)//p=pParse.aColCache... p++)
+ {
#if FALSE //* This code wold remove the entry from the cache if it existed */
p = pParse.aColCache[i];
if ( p.iReg != 0 && p.iTable == iTab && p.iColumn == iCol )
@@ -2430,1415 +2172,1268 @@ static void sqlite3ExprCacheStore( Parse pParse, int iTab, int iCol, int iReg )
return;
}
#endif
- Debug.Assert( p.iReg == 0 || p.iTable != iTab || p.iColumn != iCol );
- }
+ Debug.Assert(p.iReg == 0 || p.iTable != iTab || p.iColumn != iCol);
+ }
#endif
- /* Find an empty slot and replace it */
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++)
- {
- p = pParse.aColCache[i];
- if ( p.iReg == 0 )
- {
- p.iLevel = pParse.iCacheLevel;
- p.iTable = iTab;
- p.iColumn = iCol;
- p.iReg = iReg;
- p.tempReg = 0;
- p.lru = pParse.iCacheCnt++;
- return;
- }
- }
-
- /* Replace the last recently used */
- minLru = 0x7fffffff;
- idxLru = -1;
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache..., p++)
- {
- p = pParse.aColCache[i];
- if ( p.lru < minLru )
- {
- idxLru = i;
- minLru = p.lru;
+ /* Find an empty slot and replace it */
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)//p=pParse.aColCache... p++)
+ {
+ p = pParse.aColCache[i];
+ if (p.iReg == 0) {
+ p.iLevel = pParse.iCacheLevel;
+ p.iTable = iTab;
+ p.iColumn = iCol;
+ p.iReg = iReg;
+ p.tempReg = 0;
+ p.lru = pParse.iCacheCnt++;
+ return;
+ }
+ }
+
+ /* Replace the last recently used */
+ minLru = 0x7fffffff;
+ idxLru = -1;
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)//p=pParse.aColCache..., p++)
+ {
+ p = pParse.aColCache[i];
+ if (p.lru < minLru) {
+ idxLru = i;
+ minLru = p.lru;
+ }
+ }
+ if (ALWAYS(idxLru >= 0)) {
+ p = pParse.aColCache[idxLru];
+ p.iLevel = pParse.iCacheLevel;
+ p.iTable = iTab;
+ p.iColumn = iCol;
+ p.iReg = iReg;
+ p.tempReg = 0;
+ p.lru = pParse.iCacheCnt++;
+ return;
+ }
}
- }
- if ( ALWAYS( idxLru >= 0 ) )
- {
- p = pParse.aColCache[idxLru];
- p.iLevel = pParse.iCacheLevel;
- p.iTable = iTab;
- p.iColumn = iCol;
- p.iReg = iReg;
- p.tempReg = 0;
- p.lru = pParse.iCacheCnt++;
- return;
- }
- }
- /*
- ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
- ** Purge the range of registers from the column cache.
- */
- static void sqlite3ExprCacheRemove( Parse pParse, int iReg, int nReg )
- {
- int i;
- int iLast = iReg + nReg - 1;
- yColCache p;
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++)
- {
- p = pParse.aColCache[i];
- int r = p.iReg;
- if ( r >= iReg && r <= iLast )
- {
- cacheEntryClear( pParse, p );
- p.iReg = 0;
+ /*
+ ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
+ ** Purge the range of registers from the column cache.
+ */
+ static void sqlite3ExprCacheRemove(Parse pParse, int iReg, int nReg) {
+ int i;
+ int iLast = iReg + nReg - 1;
+ yColCache p;
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)//p=pParse.aColCache... p++)
+ {
+ p = pParse.aColCache[i];
+ int r = p.iReg;
+ if (r >= iReg && r <= iLast) {
+ cacheEntryClear(pParse, p);
+ p.iReg = 0;
+ }
+ }
}
- }
- }
- /*
- ** Remember the current column cache context. Any new entries added
- ** added to the column cache after this call are removed when the
- ** corresponding pop occurs.
- */
- static void sqlite3ExprCachePush( Parse pParse )
- {
- pParse.iCacheLevel++;
- }
+ /*
+ ** Remember the current column cache context. Any new entries added
+ ** added to the column cache after this call are removed when the
+ ** corresponding pop occurs.
+ */
+ static void sqlite3ExprCachePush(Parse pParse) {
+ pParse.iCacheLevel++;
+ }
- /*
- ** Remove from the column cache any entries that were added since the
- ** the previous N Push operations. In other words, restore the cache
- ** to the state it was in N Pushes ago.
- */
- static void sqlite3ExprCachePop( Parse pParse, int N )
- {
- int i;
- yColCache p;
- Debug.Assert( N > 0 );
- Debug.Assert( pParse.iCacheLevel >= N );
- pParse.iCacheLevel -= N;
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )// p++)
- {
- p = pParse.aColCache[i];
- if ( p.iReg != 0 && p.iLevel > pParse.iCacheLevel )
- {
- cacheEntryClear( pParse, p );
- p.iReg = 0;
+ /*
+ ** Remove from the column cache any entries that were added since the
+ ** the previous N Push operations. In other words, restore the cache
+ ** to the state it was in N Pushes ago.
+ */
+ static void sqlite3ExprCachePop(Parse pParse, int N) {
+ int i;
+ yColCache p;
+ Debug.Assert(N > 0);
+ Debug.Assert(pParse.iCacheLevel >= N);
+ pParse.iCacheLevel -= N;
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)// p++)
+ {
+ p = pParse.aColCache[i];
+ if (p.iReg != 0 && p.iLevel > pParse.iCacheLevel) {
+ cacheEntryClear(pParse, p);
+ p.iReg = 0;
+ }
+ }
}
- }
- }
- /*
- ** When a cached column is reused, make sure that its register is
- ** no longer available as a temp register. ticket #3879: that same
- ** register might be in the cache in multiple places, so be sure to
- ** get them all.
- */
- static void sqlite3ExprCachePinRegister( Parse pParse, int iReg )
- {
- int i;
- yColCache p;
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse->aColCache; iaColCache; i= 0 )
- {
- sqlite3ColumnDefault( v, pTab, iCol, regOut );
- }
- }
+ /*
+ ** Generate code to extract the value of the iCol-th column of a table.
+ */
+ static void sqlite3ExprCodeGetColumnOfTable(
+ Vdbe v, /* The VDBE under construction */
+ Table pTab, /* The table containing the value */
+ int iTabCur, /* The cursor for this table */
+ int iCol, /* Index of the column to extract */
+ int regOut /* Extract the value into this register */
+ ) {
+ if (iCol < 0 || iCol == pTab.iPKey) {
+ sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
+ } else {
+ int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
+ sqlite3VdbeAddOp3(v, op, iTabCur, iCol, regOut);
+ }
+ if (iCol >= 0) {
+ sqlite3ColumnDefault(v, pTab, iCol, regOut);
+ }
+ }
- /*
- ** Generate code that will extract the iColumn-th column from
- ** table pTab and store the column value in a register. An effort
- ** is made to store the column value in register iReg, but this is
- ** not guaranteed. The location of the column value is returned.
- **
- ** There must be an open cursor to pTab in iTable when this routine
- ** is called. If iColumn<0 then code is generated that extracts the rowid.
- */
- static int sqlite3ExprCodeGetColumn(
- Parse pParse, /* Parsing and code generating context */
- Table pTab, /* Description of the table we are reading from */
- int iColumn, /* Index of the table column */
- int iTable, /* The cursor pointing to the table */
- int iReg /* Store results here */
- )
- {
- Vdbe v = pParse.pVdbe;
- int i;
- yColCache p;
-
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )
- {// p=pParse.aColCache, p++
- p = pParse.aColCache[i];
- if ( p.iReg > 0 && p.iTable == iTable && p.iColumn == iColumn )
- {
- p.lru = pParse.iCacheCnt++;
- sqlite3ExprCachePinRegister( pParse, p.iReg );
- return p.iReg;
+ /*
+ ** Generate code that will extract the iColumn-th column from
+ ** table pTab and store the column value in a register. An effort
+ ** is made to store the column value in register iReg, but this is
+ ** not guaranteed. The location of the column value is returned.
+ **
+ ** There must be an open cursor to pTab in iTable when this routine
+ ** is called. If iColumn<0 then code is generated that extracts the rowid.
+ */
+ static int sqlite3ExprCodeGetColumn(
+ Parse pParse, /* Parsing and code generating context */
+ Table pTab, /* Description of the table we are reading from */
+ int iColumn, /* Index of the table column */
+ int iTable, /* The cursor pointing to the table */
+ int iReg /* Store results here */
+ ) {
+ Vdbe v = pParse.pVdbe;
+ int i;
+ yColCache p;
+
+ for (i = 0; i < SQLITE_N_COLCACHE; i++) {// p=pParse.aColCache, p++
+ p = pParse.aColCache[i];
+ if (p.iReg > 0 && p.iTable == iTable && p.iColumn == iColumn) {
+ p.lru = pParse.iCacheCnt++;
+ sqlite3ExprCachePinRegister(pParse, p.iReg);
+ return p.iReg;
+ }
+ }
+ Debug.Assert(v != null);
+ sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
+ sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
+ return iReg;
}
- }
- Debug.Assert( v != null );
- sqlite3ExprCodeGetColumnOfTable( v, pTab, iTable, iColumn, iReg );
- sqlite3ExprCacheStore( pParse, iTable, iColumn, iReg );
- return iReg;
- }
- /*
- ** Clear all column cache entries.
- */
- static void sqlite3ExprCacheClear( Parse pParse )
- {
- int i;
- yColCache p;
-
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )// p=pParse.aColCache... p++)
- {
- p = pParse.aColCache[i];
- if ( p.iReg != 0 )
- {
- cacheEntryClear( pParse, p );
- p.iReg = 0;
+ /*
+ ** Clear all column cache entries.
+ */
+ static void sqlite3ExprCacheClear(Parse pParse) {
+ int i;
+ yColCache p;
+
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)// p=pParse.aColCache... p++)
+ {
+ p = pParse.aColCache[i];
+ if (p.iReg != 0) {
+ cacheEntryClear(pParse, p);
+ p.iReg = 0;
+ }
+ }
}
- }
- }
- /*
- ** Record the fact that an affinity change has occurred on iCount
- ** registers starting with iStart.
- */
- static void sqlite3ExprCacheAffinityChange( Parse pParse, int iStart, int iCount )
- {
- sqlite3ExprCacheRemove( pParse, iStart, iCount );
- }
+ /*
+ ** Record the fact that an affinity change has occurred on iCount
+ ** registers starting with iStart.
+ */
+ static void sqlite3ExprCacheAffinityChange(Parse pParse, int iStart, int iCount) {
+ sqlite3ExprCacheRemove(pParse, iStart, iCount);
+ }
- /*
- ** Generate code to move content from registers iFrom...iFrom+nReg-1
- ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
- */
- static void sqlite3ExprCodeMove( Parse pParse, int iFrom, int iTo, int nReg )
- {
- int i;
- yColCache p;
- if ( NEVER( iFrom == iTo ) )
- return;
- sqlite3VdbeAddOp3( pParse.pVdbe, OP_Move, iFrom, iTo, nReg );
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )// p=pParse.aColCache... p++)
- {
- p = pParse.aColCache[i];
- int x = p.iReg;
- if ( x >= iFrom && x < iFrom + nReg )
- {
- p.iReg += iTo - iFrom;
+ /*
+ ** Generate code to move content from registers iFrom...iFrom+nReg-1
+ ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
+ */
+ static void sqlite3ExprCodeMove(Parse pParse, int iFrom, int iTo, int nReg) {
+ int i;
+ yColCache p;
+ if (NEVER(iFrom == iTo))
+ return;
+ sqlite3VdbeAddOp3(pParse.pVdbe, OP_Move, iFrom, iTo, nReg);
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)// p=pParse.aColCache... p++)
+ {
+ p = pParse.aColCache[i];
+ int x = p.iReg;
+ if (x >= iFrom && x < iFrom + nReg) {
+ p.iReg += iTo - iFrom;
+ }
+ }
}
- }
- }
- /*
- ** Generate code to copy content from registers iFrom...iFrom+nReg-1
- ** over to iTo..iTo+nReg-1.
- */
- static void sqlite3ExprCodeCopy( Parse pParse, int iFrom, int iTo, int nReg )
- {
- int i;
- if ( NEVER( iFrom == iTo ) )
- return;
- for ( i = 0; i < nReg; i++ )
- {
- sqlite3VdbeAddOp2( pParse.pVdbe, OP_Copy, iFrom + i, iTo + i );
- }
- }
+ /*
+ ** Generate code to copy content from registers iFrom...iFrom+nReg-1
+ ** over to iTo..iTo+nReg-1.
+ */
+ static void sqlite3ExprCodeCopy(Parse pParse, int iFrom, int iTo, int nReg) {
+ int i;
+ if (NEVER(iFrom == iTo))
+ return;
+ for (i = 0; i < nReg; i++) {
+ sqlite3VdbeAddOp2(pParse.pVdbe, OP_Copy, iFrom + i, iTo + i);
+ }
+ }
#if (SQLITE_DEBUG) || (SQLITE_COVERAGE_TEST)
- /*
-** Return true if any register in the range iFrom..iTo (inclusive)
-** is used as part of the column cache.
-**
-** This routine is used within Debug.Assert() and testcase() macros only
-** and does not appear in a normal build.
-*/
- static int usedAsColumnCache( Parse pParse, int iFrom, int iTo )
- {
- int i;
- yColCache p;
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++)
- {
- p = pParse.aColCache[i];
- int r = p.iReg;
- if ( r >= iFrom && r <= iTo )
- return 1; /*NO_TEST*/
- }
- return 0;
- }
+ /*
+ ** Return true if any register in the range iFrom..iTo (inclusive)
+ ** is used as part of the column cache.
+ **
+ ** This routine is used within Debug.Assert() and testcase() macros only
+ ** and does not appear in a normal build.
+ */
+ static int usedAsColumnCache(Parse pParse, int iFrom, int iTo) {
+ int i;
+ yColCache p;
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)//p=pParse.aColCache... p++)
+ {
+ p = pParse.aColCache[i];
+ int r = p.iReg;
+ if (r >= iFrom && r <= iTo)
+ return 1; /*NO_TEST*/
+ }
+ return 0;
+ }
#else
static int usedAsColumnCache( Parse pParse, int iFrom, int iTo ){return 0;}
#endif //* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
- /*
- ** Generate code into the current Vdbe to evaluate the given
- ** expression. Attempt to store the results in register "target".
- ** Return the register where results are stored.
- **
- ** With this routine, there is no guarantee that results will
- ** be stored in target. The result might be stored in some other
- ** register if it is convenient to do so. The calling function
- ** must check the return code and move the results to the desired
- ** register.
- */
- static int sqlite3ExprCodeTarget( Parse pParse, Expr pExpr, int target )
- {
- Vdbe v = pParse.pVdbe; /* The VM under construction */
- int op; /* The opcode being coded */
- int inReg = target; /* Results stored in register inReg */
- int regFree1 = 0; /* If non-zero free this temporary register */
- int regFree2 = 0; /* If non-zero free this temporary register */
- int r1 = 0, r2 = 0, r3 = 0, r4 = 0; /* Various register numbers */
- sqlite3 db = pParse.db; /* The database connection */
-
- Debug.Assert( target > 0 && target <= pParse.nMem );
- if ( v == null )
- {
- //Debug.Assert( pParse.db.mallocFailed != 0 );
- return 0;
- }
-
- if ( pExpr == null )
- {
- op = TK_NULL;
- }
- else
- {
- op = pExpr.op;
- }
- switch ( op )
- {
- case TK_AGG_COLUMN:
- {
- AggInfo pAggInfo = pExpr.pAggInfo;
- AggInfo_col pCol = pAggInfo.aCol[pExpr.iAgg];
- if ( pAggInfo.directMode == 0 )
- {
- Debug.Assert( pCol.iMem > 0 );
- inReg = pCol.iMem;
- break;
- }
- else if ( pAggInfo.useSortingIdx != 0 )
- {
- sqlite3VdbeAddOp3( v, OP_Column, pAggInfo.sortingIdx,
- pCol.iSorterColumn, target );
- break;
- }
- /* Otherwise, fall thru into the TK_COLUMN case */
- }
- goto case TK_COLUMN;
- case TK_COLUMN:
- {
- if ( pExpr.iTable < 0 )
- {
- /* This only happens when coding check constraints */
- Debug.Assert( pParse.ckBase > 0 );
- inReg = pExpr.iColumn + pParse.ckBase;
+ /*
+ ** Generate code into the current Vdbe to evaluate the given
+ ** expression. Attempt to store the results in register "target".
+ ** Return the register where results are stored.
+ **
+ ** With this routine, there is no guarantee that results will
+ ** be stored in target. The result might be stored in some other
+ ** register if it is convenient to do so. The calling function
+ ** must check the return code and move the results to the desired
+ ** register.
+ */
+ static int sqlite3ExprCodeTarget(Parse pParse, Expr pExpr, int target) {
+ Vdbe v = pParse.pVdbe; /* The VM under construction */
+ int op; /* The opcode being coded */
+ int inReg = target; /* Results stored in register inReg */
+ int regFree1 = 0; /* If non-zero free this temporary register */
+ int regFree2 = 0; /* If non-zero free this temporary register */
+ int r1 = 0, r2 = 0, r3 = 0, r4 = 0; /* Various register numbers */
+ sqlite3 db = pParse.db; /* The database connection */
+
+ Debug.Assert(target > 0 && target <= pParse.nMem);
+ if (v == null) {
+ //Debug.Assert( pParse.db.mallocFailed != 0 );
+ return 0;
}
- else
- {
- inReg = sqlite3ExprCodeGetColumn( pParse, pExpr.pTab,
- pExpr.iColumn, pExpr.iTable, target );
+
+ if (pExpr == null) {
+ op = TK_NULL;
+ } else {
+ op = pExpr.op;
}
- break;
- }
- case TK_INTEGER:
- {
- codeInteger( pParse, pExpr, false, target );
- break;
- }
+ switch (op) {
+ case TK_AGG_COLUMN: {
+ AggInfo pAggInfo = pExpr.pAggInfo;
+ AggInfo_col pCol = pAggInfo.aCol[pExpr.iAgg];
+ if (pAggInfo.directMode == 0) {
+ Debug.Assert(pCol.iMem > 0);
+ inReg = pCol.iMem;
+ break;
+ } else if (pAggInfo.useSortingIdx != 0) {
+ sqlite3VdbeAddOp3(v, OP_Column, pAggInfo.sortingIdx,
+ pCol.iSorterColumn, target);
+ break;
+ }
+ /* Otherwise, fall thru into the TK_COLUMN case */
+ }
+ goto case TK_COLUMN;
+ case TK_COLUMN: {
+ if (pExpr.iTable < 0) {
+ /* This only happens when coding check constraints */
+ Debug.Assert(pParse.ckBase > 0);
+ inReg = pExpr.iColumn + pParse.ckBase;
+ } else {
+ inReg = sqlite3ExprCodeGetColumn(pParse, pExpr.pTab,
+ pExpr.iColumn, pExpr.iTable, target);
+ }
+ break;
+ }
+ case TK_INTEGER: {
+ codeInteger(pParse, pExpr, false, target);
+ break;
+ }
#if !SQLITE_OMIT_FLOATING_POINT
- case TK_FLOAT:
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- codeReal( v, pExpr.u.zToken, false, target );
- break;
- }
+ case TK_FLOAT: {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ codeReal(v, pExpr.u.zToken, false, target);
+ break;
+ }
#endif
- case TK_STRING:
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- sqlite3VdbeAddOp4( v, OP_String8, 0, target, 0, pExpr.u.zToken, 0 );
- break;
- }
- case TK_NULL:
- {
- sqlite3VdbeAddOp2( v, OP_Null, 0, target );
- break;
- }
+ case TK_STRING: {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr.u.zToken, 0);
+ break;
+ }
+ case TK_NULL: {
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ break;
+ }
#if !SQLITE_OMIT_BLOB_LITERAL
- case TK_BLOB:
- {
- int n;
- string z;
- byte[] zBlob;
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- Debug.Assert( pExpr.u.zToken[0] == 'x' || pExpr.u.zToken[0] == 'X' );
- Debug.Assert( pExpr.u.zToken[1] == '\'' );
- z = pExpr.u.zToken.Substring( 2 );
- n = sqlite3Strlen30( z ) - 1;
- Debug.Assert( z[n] == '\'' );
- zBlob = sqlite3HexToBlob( sqlite3VdbeDb( v ), z, n );
- sqlite3VdbeAddOp4( v, OP_Blob, n / 2, target, 0, zBlob, P4_DYNAMIC );
- break;
- }
+ case TK_BLOB: {
+ int n;
+ string z;
+ byte[] zBlob;
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ Debug.Assert(pExpr.u.zToken[0] == 'x' || pExpr.u.zToken[0] == 'X');
+ Debug.Assert(pExpr.u.zToken[1] == '\'');
+ z = pExpr.u.zToken.Substring(2);
+ n = sqlite3Strlen30(z) - 1;
+ Debug.Assert(z[n] == '\'');
+ zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
+ sqlite3VdbeAddOp4(v, OP_Blob, n / 2, target, 0, zBlob, P4_DYNAMIC);
+ break;
+ }
#endif
- case TK_VARIABLE:
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- Debug.Assert( pExpr.u.zToken != null );
- Debug.Assert( pExpr.u.zToken.Length != 0 );
- sqlite3VdbeAddOp2( v, OP_Variable, pExpr.iColumn, target );
- if ( pExpr.u.zToken.Length > 1 )
- {
- Debug.Assert( pExpr.u.zToken[0] == '?'
- || string.Equals(pExpr.u.zToken, pParse.azVar[pExpr.iColumn - 1], StringComparison.Ordinal) );
- sqlite3VdbeChangeP4( v, -1, pParse.azVar[pExpr.iColumn - 1], P4_STATIC );
- }
- break;
- }
- case TK_REGISTER:
- {
- inReg = pExpr.iTable;
- break;
- }
- case TK_AS:
- {
- inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target );
- break;
- }
+ case TK_VARIABLE: {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ Debug.Assert(pExpr.u.zToken != null);
+ Debug.Assert(pExpr.u.zToken.Length != 0);
+ sqlite3VdbeAddOp2(v, OP_Variable, pExpr.iColumn, target);
+ if (pExpr.u.zToken.Length > 1) {
+ Debug.Assert(pExpr.u.zToken[0] == '?'
+ || string.Equals(pExpr.u.zToken, pParse.azVar[pExpr.iColumn - 1], StringComparison.Ordinal));
+ sqlite3VdbeChangeP4(v, -1, pParse.azVar[pExpr.iColumn - 1], P4_STATIC);
+ }
+ break;
+ }
+ case TK_REGISTER: {
+ inReg = pExpr.iTable;
+ break;
+ }
+ case TK_AS: {
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr.pLeft, target);
+ break;
+ }
#if !SQLITE_OMIT_CAST
- case TK_CAST:
- {
- /* Expressions of the form: CAST(pLeft AS token) */
- int aff, to_op;
- inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target );
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- aff = sqlite3AffinityType( pExpr.u.zToken );
- to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
- Debug.Assert( to_op == OP_ToText || aff != SQLITE_AFF_TEXT );
- Debug.Assert( to_op == OP_ToBlob || aff != SQLITE_AFF_NONE );
- Debug.Assert( to_op == OP_ToNumeric || aff != SQLITE_AFF_NUMERIC );
- Debug.Assert( to_op == OP_ToInt || aff != SQLITE_AFF_INTEGER );
- Debug.Assert( to_op == OP_ToReal || aff != SQLITE_AFF_REAL );
- testcase( to_op == OP_ToText );
- testcase( to_op == OP_ToBlob );
- testcase( to_op == OP_ToNumeric );
- testcase( to_op == OP_ToInt );
- testcase( to_op == OP_ToReal );
- if ( inReg != target )
- {
- sqlite3VdbeAddOp2( v, OP_SCopy, inReg, target );
- inReg = target;
- }
- sqlite3VdbeAddOp1( v, to_op, inReg );
- testcase( usedAsColumnCache( pParse, inReg, inReg ) != 0 );
- sqlite3ExprCacheAffinityChange( pParse, inReg, 1 );
- break;
- }
+ case TK_CAST: {
+ /* Expressions of the form: CAST(pLeft AS token) */
+ int aff, to_op;
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr.pLeft, target);
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ aff = sqlite3AffinityType(pExpr.u.zToken);
+ to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
+ Debug.Assert(to_op == OP_ToText || aff != SQLITE_AFF_TEXT);
+ Debug.Assert(to_op == OP_ToBlob || aff != SQLITE_AFF_NONE);
+ Debug.Assert(to_op == OP_ToNumeric || aff != SQLITE_AFF_NUMERIC);
+ Debug.Assert(to_op == OP_ToInt || aff != SQLITE_AFF_INTEGER);
+ Debug.Assert(to_op == OP_ToReal || aff != SQLITE_AFF_REAL);
+ testcase(to_op == OP_ToText);
+ testcase(to_op == OP_ToBlob);
+ testcase(to_op == OP_ToNumeric);
+ testcase(to_op == OP_ToInt);
+ testcase(to_op == OP_ToReal);
+ if (inReg != target) {
+ sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
+ inReg = target;
+ }
+ sqlite3VdbeAddOp1(v, to_op, inReg);
+ testcase(usedAsColumnCache(pParse, inReg, inReg) != 0);
+ sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
+ break;
+ }
#endif // * SQLITE_OMIT_CAST */
- case TK_LT:
- case TK_LE:
- case TK_GT:
- case TK_GE:
- case TK_NE:
- case TK_EQ:
- {
- Debug.Assert( TK_LT == OP_Lt );
- Debug.Assert( TK_LE == OP_Le );
- Debug.Assert( TK_GT == OP_Gt );
- Debug.Assert( TK_GE == OP_Ge );
- Debug.Assert( TK_EQ == OP_Eq );
- Debug.Assert( TK_NE == OP_Ne );
- testcase( op == TK_LT );
- testcase( op == TK_LE );
- testcase( op == TK_GT );
- testcase( op == TK_GE );
- testcase( op == TK_EQ );
- testcase( op == TK_NE );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op,
- r1, r2, inReg, SQLITE_STOREP2 );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_IS:
- case TK_ISNOT:
- {
- testcase( op == TK_IS );
- testcase( op == TK_ISNOT );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- op = ( op == TK_IS ) ? TK_EQ : TK_NE;
- codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op,
- r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_AND:
- case TK_OR:
- case TK_PLUS:
- case TK_STAR:
- case TK_MINUS:
- case TK_REM:
- case TK_BITAND:
- case TK_BITOR:
- case TK_SLASH:
- case TK_LSHIFT:
- case TK_RSHIFT:
- case TK_CONCAT:
- {
- Debug.Assert( TK_AND == OP_And );
- Debug.Assert( TK_OR == OP_Or );
- Debug.Assert( TK_PLUS == OP_Add );
- Debug.Assert( TK_MINUS == OP_Subtract );
- Debug.Assert( TK_REM == OP_Remainder );
- Debug.Assert( TK_BITAND == OP_BitAnd );
- Debug.Assert( TK_BITOR == OP_BitOr );
- Debug.Assert( TK_SLASH == OP_Divide );
- Debug.Assert( TK_LSHIFT == OP_ShiftLeft );
- Debug.Assert( TK_RSHIFT == OP_ShiftRight );
- Debug.Assert( TK_CONCAT == OP_Concat );
- testcase( op == TK_AND );
- testcase( op == TK_OR );
- testcase( op == TK_PLUS );
- testcase( op == TK_MINUS );
- testcase( op == TK_REM );
- testcase( op == TK_BITAND );
- testcase( op == TK_BITOR );
- testcase( op == TK_SLASH );
- testcase( op == TK_LSHIFT );
- testcase( op == TK_RSHIFT );
- testcase( op == TK_CONCAT );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- sqlite3VdbeAddOp3( v, op, r2, r1, target );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_UMINUS:
- {
- Expr pLeft = pExpr.pLeft;
- Debug.Assert( pLeft != null );
- if ( pLeft.op == TK_INTEGER )
- {
- codeInteger( pParse, pLeft, true, target );
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_NE:
+ case TK_EQ: {
+ Debug.Assert(TK_LT == OP_Lt);
+ Debug.Assert(TK_LE == OP_Le);
+ Debug.Assert(TK_GT == OP_Gt);
+ Debug.Assert(TK_GE == OP_Ge);
+ Debug.Assert(TK_EQ == OP_Eq);
+ Debug.Assert(TK_NE == OP_Ne);
+ testcase(op == TK_LT);
+ testcase(op == TK_LE);
+ testcase(op == TK_GT);
+ testcase(op == TK_GE);
+ testcase(op == TK_EQ);
+ testcase(op == TK_NE);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ codeCompare(pParse, pExpr.pLeft, pExpr.pRight, op,
+ r1, r2, inReg, SQLITE_STOREP2);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_IS:
+ case TK_ISNOT: {
+ testcase(op == TK_IS);
+ testcase(op == TK_ISNOT);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ op = (op == TK_IS) ? TK_EQ : TK_NE;
+ codeCompare(pParse, pExpr.pLeft, pExpr.pRight, op,
+ r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_AND:
+ case TK_OR:
+ case TK_PLUS:
+ case TK_STAR:
+ case TK_MINUS:
+ case TK_REM:
+ case TK_BITAND:
+ case TK_BITOR:
+ case TK_SLASH:
+ case TK_LSHIFT:
+ case TK_RSHIFT:
+ case TK_CONCAT: {
+ Debug.Assert(TK_AND == OP_And);
+ Debug.Assert(TK_OR == OP_Or);
+ Debug.Assert(TK_PLUS == OP_Add);
+ Debug.Assert(TK_MINUS == OP_Subtract);
+ Debug.Assert(TK_REM == OP_Remainder);
+ Debug.Assert(TK_BITAND == OP_BitAnd);
+ Debug.Assert(TK_BITOR == OP_BitOr);
+ Debug.Assert(TK_SLASH == OP_Divide);
+ Debug.Assert(TK_LSHIFT == OP_ShiftLeft);
+ Debug.Assert(TK_RSHIFT == OP_ShiftRight);
+ Debug.Assert(TK_CONCAT == OP_Concat);
+ testcase(op == TK_AND);
+ testcase(op == TK_OR);
+ testcase(op == TK_PLUS);
+ testcase(op == TK_MINUS);
+ testcase(op == TK_REM);
+ testcase(op == TK_BITAND);
+ testcase(op == TK_BITOR);
+ testcase(op == TK_SLASH);
+ testcase(op == TK_LSHIFT);
+ testcase(op == TK_RSHIFT);
+ testcase(op == TK_CONCAT);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ sqlite3VdbeAddOp3(v, op, r2, r1, target);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_UMINUS: {
+ Expr pLeft = pExpr.pLeft;
+ Debug.Assert(pLeft != null);
+ if (pLeft.op == TK_INTEGER) {
+ codeInteger(pParse, pLeft, true, target);
#if !SQLITE_OMIT_FLOATING_POINT
- }
- else if ( pLeft.op == TK_FLOAT )
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- codeReal( v, pLeft.u.zToken, true, target );
+ } else if (pLeft.op == TK_FLOAT) {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ codeReal(v, pLeft.u.zToken, true, target);
#endif
- }
- else
- {
- regFree1 = r1 = sqlite3GetTempReg( pParse );
- sqlite3VdbeAddOp2( v, OP_Integer, 0, r1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree2 );
- sqlite3VdbeAddOp3( v, OP_Subtract, r2, r1, target );
- testcase( regFree2 == 0 );
- }
- inReg = target;
- break;
- }
- case TK_BITNOT:
- case TK_NOT:
- {
- Debug.Assert( TK_BITNOT == OP_BitNot );
- Debug.Assert( TK_NOT == OP_Not );
- testcase( op == TK_BITNOT );
- testcase( op == TK_NOT );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- testcase( regFree1 == 0 );
- inReg = target;
- sqlite3VdbeAddOp2( v, op, r1, inReg );
- break;
- }
- case TK_ISNULL:
- case TK_NOTNULL:
- {
- int addr;
- Debug.Assert( TK_ISNULL == OP_IsNull );
- Debug.Assert( TK_NOTNULL == OP_NotNull );
- testcase( op == TK_ISNULL );
- testcase( op == TK_NOTNULL );
- sqlite3VdbeAddOp2( v, OP_Integer, 1, target );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- testcase( regFree1 == 0 );
- addr = sqlite3VdbeAddOp1( v, op, r1 );
- sqlite3VdbeAddOp2( v, OP_AddImm, target, -1 );
- sqlite3VdbeJumpHere( v, addr );
- break;
- }
- case TK_AGG_FUNCTION:
- {
- AggInfo pInfo = pExpr.pAggInfo;
- if ( pInfo == null )
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- sqlite3ErrorMsg( pParse, "misuse of aggregate: %s()", pExpr.u.zToken );
- }
- else
- {
- inReg = pInfo.aFunc[pExpr.iAgg].iMem;
- }
- break;
- }
- case TK_CONST_FUNC:
- case TK_FUNCTION:
- {
- ExprList pFarg; /* List of function arguments */
- int nFarg; /* Number of function arguments */
- FuncDef pDef; /* The function definition object */
- int nId; /* Length of the function name in bytes */
- string zId; /* The function name */
- int constMask = 0; /* Mask of function arguments that are constant */
- int i; /* Loop counter */
- u8 enc = ENC( db ); /* The text encoding used by this database */
- CollSeq pColl = null; /* A collating sequence */
-
- Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) );
- testcase( op == TK_CONST_FUNC );
- testcase( op == TK_FUNCTION );
- if ( ExprHasAnyProperty( pExpr, EP_TokenOnly ) )
- {
- pFarg = null;
- }
- else
- {
- pFarg = pExpr.x.pList;
- }
- nFarg = pFarg != null ? pFarg.nExpr : 0;
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- zId = pExpr.u.zToken;
- nId = sqlite3Strlen30( zId );
- pDef = sqlite3FindFunction( pParse.db, zId, nId, nFarg, enc, 0 );
- if ( pDef == null )
- {
- sqlite3ErrorMsg( pParse, "unknown function: %.*s()", nId, zId );
- break;
- }
+ } else {
+ regFree1 = r1 = sqlite3GetTempReg(pParse);
+ sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree2);
+ sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
+ testcase(regFree2 == 0);
+ }
+ inReg = target;
+ break;
+ }
+ case TK_BITNOT:
+ case TK_NOT: {
+ Debug.Assert(TK_BITNOT == OP_BitNot);
+ Debug.Assert(TK_NOT == OP_Not);
+ testcase(op == TK_BITNOT);
+ testcase(op == TK_NOT);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ testcase(regFree1 == 0);
+ inReg = target;
+ sqlite3VdbeAddOp2(v, op, r1, inReg);
+ break;
+ }
+ case TK_ISNULL:
+ case TK_NOTNULL: {
+ int addr;
+ Debug.Assert(TK_ISNULL == OP_IsNull);
+ Debug.Assert(TK_NOTNULL == OP_NotNull);
+ testcase(op == TK_ISNULL);
+ testcase(op == TK_NOTNULL);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ testcase(regFree1 == 0);
+ addr = sqlite3VdbeAddOp1(v, op, r1);
+ sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
+ sqlite3VdbeJumpHere(v, addr);
+ break;
+ }
+ case TK_AGG_FUNCTION: {
+ AggInfo pInfo = pExpr.pAggInfo;
+ if (pInfo == null) {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr.u.zToken);
+ } else {
+ inReg = pInfo.aFunc[pExpr.iAgg].iMem;
+ }
+ break;
+ }
+ case TK_CONST_FUNC:
+ case TK_FUNCTION: {
+ ExprList pFarg; /* List of function arguments */
+ int nFarg; /* Number of function arguments */
+ FuncDef pDef; /* The function definition object */
+ int nId; /* Length of the function name in bytes */
+ string zId; /* The function name */
+ int constMask = 0; /* Mask of function arguments that are constant */
+ int i; /* Loop counter */
+ u8 enc = ENC(db); /* The text encoding used by this database */
+ CollSeq pColl = null; /* A collating sequence */
+
+ Debug.Assert(!ExprHasProperty(pExpr, EP_xIsSelect));
+ testcase(op == TK_CONST_FUNC);
+ testcase(op == TK_FUNCTION);
+ if (ExprHasAnyProperty(pExpr, EP_TokenOnly)) {
+ pFarg = null;
+ } else {
+ pFarg = pExpr.x.pList;
+ }
+ nFarg = pFarg != null ? pFarg.nExpr : 0;
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ zId = pExpr.u.zToken;
+ nId = sqlite3Strlen30(zId);
+ pDef = sqlite3FindFunction(pParse.db, zId, nId, nFarg, enc, 0);
+ if (pDef == null) {
+ sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
+ break;
+ }
- /* Attempt a direct implementation of the built-in COALESCE() and
- ** IFNULL() functions. This avoids unnecessary evalation of
- ** arguments past the first non-NULL argument.
- */
- if ( ( pDef.flags & SQLITE_FUNC_COALESCE ) != 0 )
- {
- int endCoalesce = sqlite3VdbeMakeLabel( v );
- Debug.Assert( nFarg >= 2 );
- sqlite3ExprCode( pParse, pFarg.a[0].pExpr, target );
- for ( i = 1; i < nFarg; i++ )
- {
- sqlite3VdbeAddOp2( v, OP_NotNull, target, endCoalesce );
- sqlite3ExprCacheRemove( pParse, target, 1 );
- sqlite3ExprCachePush( pParse );
- sqlite3ExprCode( pParse, pFarg.a[i].pExpr, target );
- sqlite3ExprCachePop( pParse, 1 );
- }
- sqlite3VdbeResolveLabel( v, endCoalesce );
- break;
- }
+ /* Attempt a direct implementation of the built-in COALESCE() and
+ ** IFNULL() functions. This avoids unnecessary evalation of
+ ** arguments past the first non-NULL argument.
+ */
+ if ((pDef.flags & SQLITE_FUNC_COALESCE) != 0) {
+ int endCoalesce = sqlite3VdbeMakeLabel(v);
+ Debug.Assert(nFarg >= 2);
+ sqlite3ExprCode(pParse, pFarg.a[0].pExpr, target);
+ for (i = 1; i < nFarg; i++) {
+ sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
+ sqlite3ExprCacheRemove(pParse, target, 1);
+ sqlite3ExprCachePush(pParse);
+ sqlite3ExprCode(pParse, pFarg.a[i].pExpr, target);
+ sqlite3ExprCachePop(pParse, 1);
+ }
+ sqlite3VdbeResolveLabel(v, endCoalesce);
+ break;
+ }
- if ( pFarg != null )
- {
- r1 = sqlite3GetTempRange( pParse, nFarg );
- sqlite3ExprCachePush( pParse ); /* Ticket 2ea2425d34be */
- sqlite3ExprCodeExprList( pParse, pFarg, r1, true );
- sqlite3ExprCachePop( pParse, 1 ); /* Ticket 2ea2425d34be */
- }
- else
- {
- r1 = 0;
- }
+ if (pFarg != null) {
+ r1 = sqlite3GetTempRange(pParse, nFarg);
+ sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
+ sqlite3ExprCodeExprList(pParse, pFarg, r1, true);
+ sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
+ } else {
+ r1 = 0;
+ }
#if !SQLITE_OMIT_VIRTUALTABLE
-/* Possibly overload the function if the first argument is
-** a virtual table column.
-**
-** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
-** second argument, not the first, as the argument to test to
-** see if it is a column in a virtual table. This is done because
-** the left operand of infix functions (the operand we want to
-** control overloading) ends up as the second argument to the
-** function. The expression "A glob B" is equivalent to
-** "glob(B,A). We want to use the A in "A glob B" to test
-** for function overloading. But we use the B term in "glob(B,A)".
-*/
- if ( nFarg >= 2 && ( pExpr.flags & EP_InfixFunc ) != 0 )
- {
- pDef = sqlite3VtabOverloadFunction( db, pDef, nFarg, pFarg.a[1].pExpr );
- }
- else if ( nFarg > 0 )
- {
- pDef = sqlite3VtabOverloadFunction( db, pDef, nFarg, pFarg.a[0].pExpr );
- }
+ /* Possibly overload the function if the first argument is
+ ** a virtual table column.
+ **
+ ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
+ ** second argument, not the first, as the argument to test to
+ ** see if it is a column in a virtual table. This is done because
+ ** the left operand of infix functions (the operand we want to
+ ** control overloading) ends up as the second argument to the
+ ** function. The expression "A glob B" is equivalent to
+ ** "glob(B,A). We want to use the A in "A glob B" to test
+ ** for function overloading. But we use the B term in "glob(B,A)".
+ */
+ if (nFarg >= 2 && (pExpr.flags & EP_InfixFunc) != 0) {
+ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg.a[1].pExpr);
+ } else if (nFarg > 0) {
+ pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg.a[0].pExpr);
+ }
#endif
- for ( i = 0; i < nFarg; i++ )
- {
- if ( i < 32 && sqlite3ExprIsConstant( pFarg.a[i].pExpr ) != 0 )
- {
- constMask |= ( 1 << i );
- }
- if ( ( pDef.flags & SQLITE_FUNC_NEEDCOLL ) != 0 && null == pColl )
- {
- pColl = sqlite3ExprCollSeq( pParse, pFarg.a[i].pExpr );
- }
- }
- if ( ( pDef.flags & SQLITE_FUNC_NEEDCOLL ) != 0 )
- {
- if ( null == pColl )
- pColl = db.pDfltColl;
- sqlite3VdbeAddOp4( v, OP_CollSeq, 0, 0, 0, pColl, P4_COLLSEQ );
- }
- sqlite3VdbeAddOp4( v, OP_Function, constMask, r1, target,
- pDef, P4_FUNCDEF );
- sqlite3VdbeChangeP5( v, (u8)nFarg );
- if ( nFarg != 0 )
- {
- sqlite3ReleaseTempRange( pParse, r1, nFarg );
- }
- break;
- }
+ for (i = 0; i < nFarg; i++) {
+ if (i < 32 && sqlite3ExprIsConstant(pFarg.a[i].pExpr) != 0) {
+ constMask |= (1 << i);
+ }
+ if ((pDef.flags & SQLITE_FUNC_NEEDCOLL) != 0 && null == pColl) {
+ pColl = sqlite3ExprCollSeq(pParse, pFarg.a[i].pExpr);
+ }
+ }
+ if ((pDef.flags & SQLITE_FUNC_NEEDCOLL) != 0) {
+ if (null == pColl)
+ pColl = db.pDfltColl;
+ sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, pColl, P4_COLLSEQ);
+ }
+ sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
+ pDef, P4_FUNCDEF);
+ sqlite3VdbeChangeP5(v, (u8)nFarg);
+ if (nFarg != 0) {
+ sqlite3ReleaseTempRange(pParse, r1, nFarg);
+ }
+ break;
+ }
#if !SQLITE_OMIT_SUBQUERY
- case TK_EXISTS:
- case TK_SELECT:
- {
- testcase( op == TK_EXISTS );
- testcase( op == TK_SELECT );
- inReg = sqlite3CodeSubselect( pParse, pExpr, 0, false );
- break;
- }
- case TK_IN:
- {
- int destIfFalse = sqlite3VdbeMakeLabel( v );
- int destIfNull = sqlite3VdbeMakeLabel( v );
- sqlite3VdbeAddOp2( v, OP_Null, 0, target );
- sqlite3ExprCodeIN( pParse, pExpr, destIfFalse, destIfNull );
- sqlite3VdbeAddOp2( v, OP_Integer, 1, target );
- sqlite3VdbeResolveLabel( v, destIfFalse );
- sqlite3VdbeAddOp2( v, OP_AddImm, target, 0 );
- sqlite3VdbeResolveLabel( v, destIfNull );
- break;
- }
+ case TK_EXISTS:
+ case TK_SELECT: {
+ testcase(op == TK_EXISTS);
+ testcase(op == TK_SELECT);
+ inReg = sqlite3CodeSubselect(pParse, pExpr, 0, false);
+ break;
+ }
+ case TK_IN: {
+ int destIfFalse = sqlite3VdbeMakeLabel(v);
+ int destIfNull = sqlite3VdbeMakeLabel(v);
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
+ sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
+ sqlite3VdbeResolveLabel(v, destIfFalse);
+ sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
+ sqlite3VdbeResolveLabel(v, destIfNull);
+ break;
+ }
#endif //* SQLITE_OMIT_SUBQUERY */
- /*
-** x BETWEEN y AND z
-**
-** This is equivalent to
-**
-** x>=y AND x<=z
-**
-** X is stored in pExpr.pLeft.
-** Y is stored in pExpr.x.pList.a[0].pExpr.
-** Z is stored in pExpr.x.pList.a[1].pExpr.
-*/
- case TK_BETWEEN:
- {
- Expr pLeft = pExpr.pLeft;
- ExprList_item pLItem = pExpr.x.pList.a[0];
- Expr pRight = pLItem.pExpr;
- r1 = sqlite3ExprCodeTemp( pParse, pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pRight, ref regFree2 );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- r3 = sqlite3GetTempReg( pParse );
- r4 = sqlite3GetTempReg( pParse );
- codeCompare( pParse, pLeft, pRight, OP_Ge,
- r1, r2, r3, SQLITE_STOREP2 );
- pLItem = pExpr.x.pList.a[1];// pLItem++;
- pRight = pLItem.pExpr;
- sqlite3ReleaseTempReg( pParse, regFree2 );
- r2 = sqlite3ExprCodeTemp( pParse, pRight, ref regFree2 );
- testcase( regFree2 == 0 );
- codeCompare( pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2 );
- sqlite3VdbeAddOp3( v, OP_And, r3, r4, target );
- sqlite3ReleaseTempReg( pParse, r3 );
- sqlite3ReleaseTempReg( pParse, r4 );
- break;
- }
- case TK_UPLUS:
- {
- inReg = sqlite3ExprCodeTarget( pParse, pExpr.pLeft, target );
- break;
- }
- case TK_TRIGGER:
- {
- /* If the opcode is TK_TRIGGER, then the expression is a reference
- ** to a column in the new.* or old.* pseudo-tables available to
- ** trigger programs. In this case Expr.iTable is set to 1 for the
- ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
- ** is set to the column of the pseudo-table to read, or to -1 to
- ** read the rowid field.
- **
- ** The expression is implemented using an OP_Param opcode. The p1
- ** parameter is set to 0 for an old.rowid reference, or to (i+1)
- ** to reference another column of the old.* pseudo-table, where
- ** i is the index of the column. For a new.rowid reference, p1 is
- ** set to (n+1), where n is the number of columns in each pseudo-table.
- ** For a reference to any other column in the new.* pseudo-table, p1
- ** is set to (n+2+i), where n and i are as defined previously. For
- ** example, if the table on which triggers are being fired is
- ** declared as:
- **
- ** CREATE TABLE t1(a, b);
- **
- ** Then p1 is interpreted as follows:
- **
- ** p1==0 . old.rowid p1==3 . new.rowid
- ** p1==1 . old.a p1==4 . new.a
- ** p1==2 . old.b p1==5 . new.b
- */
- Table pTab = pExpr.pTab;
- int p1 = pExpr.iTable * ( pTab.nCol + 1 ) + 1 + pExpr.iColumn;
-
- Debug.Assert( pExpr.iTable == 0 || pExpr.iTable == 1 );
- Debug.Assert( pExpr.iColumn >= -1 && pExpr.iColumn < pTab.nCol );
- Debug.Assert( pTab.iPKey < 0 || pExpr.iColumn != pTab.iPKey );
- Debug.Assert( p1 >= 0 && p1 < ( pTab.nCol * 2 + 2 ) );
-
- sqlite3VdbeAddOp2( v, OP_Param, p1, target );
- VdbeComment( v, "%s.%s -> $%d",
- ( pExpr.iTable != 0 ? "new" : "old" ),
- ( pExpr.iColumn < 0 ? "rowid" : pExpr.pTab.aCol[pExpr.iColumn].zName ),
- target
- );
-
- /* If the column has REAL affinity, it may currently be stored as an
- ** integer. Use OP_RealAffinity to make sure it is really real. */
- if ( pExpr.iColumn >= 0
- && pTab.aCol[pExpr.iColumn].affinity == SQLITE_AFF_REAL
- )
- {
- sqlite3VdbeAddOp1( v, OP_RealAffinity, target );
- }
- break;
- }
-
- /*
- ** Form A:
- ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
+ /*
+ ** x BETWEEN y AND z
**
- ** Form B:
- ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
+ ** This is equivalent to
**
- ** Form A is can be transformed into the equivalent form B as follows:
- ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
- ** WHEN x=eN THEN rN ELSE y END
+ ** x>=y AND x<=z
**
- ** X (if it exists) is in pExpr.pLeft.
- ** Y is in pExpr.pRight. The Y is also optional. If there is no
- ** ELSE clause and no other term matches, then the result of the
- ** exprssion is NULL.
- ** Ei is in pExpr.x.pList.a[i*2] and Ri is pExpr.x.pList.a[i*2+1].
- **
- ** The result of the expression is the Ri for the first matching Ei,
- ** or if there is no matching Ei, the ELSE term Y, or if there is
- ** no ELSE term, NULL.
+ ** X is stored in pExpr.pLeft.
+ ** Y is stored in pExpr.x.pList.a[0].pExpr.
+ ** Z is stored in pExpr.x.pList.a[1].pExpr.
*/
- default:
- {
- Debug.Assert( op == TK_CASE );
- int endLabel; /* GOTO label for end of CASE stmt */
- int nextCase; /* GOTO label for next WHEN clause */
- int nExpr; /* 2x number of WHEN terms */
- int i; /* Loop counter */
- ExprList pEList; /* List of WHEN terms */
- ExprList_item[] aListelem; /* Array of WHEN terms */
- Expr opCompare = new Expr(); /* The X==Ei expression */
- Expr cacheX; /* Cached expression X */
- Expr pX; /* The X expression */
- Expr pTest = null; /* X==Ei (form A) or just Ei (form B) */
+ case TK_BETWEEN: {
+ Expr pLeft = pExpr.pLeft;
+ ExprList_item pLItem = pExpr.x.pList.a[0];
+ Expr pRight = pLItem.pExpr;
+ r1 = sqlite3ExprCodeTemp(pParse, pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pRight, ref regFree2);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ r3 = sqlite3GetTempReg(pParse);
+ r4 = sqlite3GetTempReg(pParse);
+ codeCompare(pParse, pLeft, pRight, OP_Ge,
+ r1, r2, r3, SQLITE_STOREP2);
+ pLItem = pExpr.x.pList.a[1];// pLItem++;
+ pRight = pLItem.pExpr;
+ sqlite3ReleaseTempReg(pParse, regFree2);
+ r2 = sqlite3ExprCodeTemp(pParse, pRight, ref regFree2);
+ testcase(regFree2 == 0);
+ codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
+ sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
+ sqlite3ReleaseTempReg(pParse, r3);
+ sqlite3ReleaseTempReg(pParse, r4);
+ break;
+ }
+ case TK_UPLUS: {
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr.pLeft, target);
+ break;
+ }
+ case TK_TRIGGER: {
+ /* If the opcode is TK_TRIGGER, then the expression is a reference
+ ** to a column in the new.* or old.* pseudo-tables available to
+ ** trigger programs. In this case Expr.iTable is set to 1 for the
+ ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
+ ** is set to the column of the pseudo-table to read, or to -1 to
+ ** read the rowid field.
+ **
+ ** The expression is implemented using an OP_Param opcode. The p1
+ ** parameter is set to 0 for an old.rowid reference, or to (i+1)
+ ** to reference another column of the old.* pseudo-table, where
+ ** i is the index of the column. For a new.rowid reference, p1 is
+ ** set to (n+1), where n is the number of columns in each pseudo-table.
+ ** For a reference to any other column in the new.* pseudo-table, p1
+ ** is set to (n+2+i), where n and i are as defined previously. For
+ ** example, if the table on which triggers are being fired is
+ ** declared as:
+ **
+ ** CREATE TABLE t1(a, b);
+ **
+ ** Then p1 is interpreted as follows:
+ **
+ ** p1==0 . old.rowid p1==3 . new.rowid
+ ** p1==1 . old.a p1==4 . new.a
+ ** p1==2 . old.b p1==5 . new.b
+ */
+ Table pTab = pExpr.pTab;
+ int p1 = pExpr.iTable * (pTab.nCol + 1) + 1 + pExpr.iColumn;
+
+ Debug.Assert(pExpr.iTable == 0 || pExpr.iTable == 1);
+ Debug.Assert(pExpr.iColumn >= -1 && pExpr.iColumn < pTab.nCol);
+ Debug.Assert(pTab.iPKey < 0 || pExpr.iColumn != pTab.iPKey);
+ Debug.Assert(p1 >= 0 && p1 < (pTab.nCol * 2 + 2));
+
+ sqlite3VdbeAddOp2(v, OP_Param, p1, target);
+ VdbeComment(v, "%s.%s -> $%d",
+ (pExpr.iTable != 0 ? "new" : "old"),
+ (pExpr.iColumn < 0 ? "rowid" : pExpr.pTab.aCol[pExpr.iColumn].zName),
+ target
+ );
+
+ /* If the column has REAL affinity, it may currently be stored as an
+ ** integer. Use OP_RealAffinity to make sure it is really real. */
+ if (pExpr.iColumn >= 0
+ && pTab.aCol[pExpr.iColumn].affinity == SQLITE_AFF_REAL
+ ) {
+ sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
+ }
+ break;
+ }
+
+ /*
+ ** Form A:
+ ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
+ **
+ ** Form B:
+ ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
+ **
+ ** Form A is can be transformed into the equivalent form B as follows:
+ ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
+ ** WHEN x=eN THEN rN ELSE y END
+ **
+ ** X (if it exists) is in pExpr.pLeft.
+ ** Y is in pExpr.pRight. The Y is also optional. If there is no
+ ** ELSE clause and no other term matches, then the result of the
+ ** exprssion is NULL.
+ ** Ei is in pExpr.x.pList.a[i*2] and Ri is pExpr.x.pList.a[i*2+1].
+ **
+ ** The result of the expression is the Ri for the first matching Ei,
+ ** or if there is no matching Ei, the ELSE term Y, or if there is
+ ** no ELSE term, NULL.
+ */
+ default: {
+ Debug.Assert(op == TK_CASE);
+ int endLabel; /* GOTO label for end of CASE stmt */
+ int nextCase; /* GOTO label for next WHEN clause */
+ int nExpr; /* 2x number of WHEN terms */
+ int i; /* Loop counter */
+ ExprList pEList; /* List of WHEN terms */
+ ExprList_item[] aListelem; /* Array of WHEN terms */
+ Expr opCompare = new Expr(); /* The X==Ei expression */
+ Expr cacheX; /* Cached expression X */
+ Expr pX; /* The X expression */
+ Expr pTest = null; /* X==Ei (form A) or just Ei (form B) */
#if !NDEBUG
- int iCacheLevel = pParse.iCacheLevel;
- //VVA_ONLY( int iCacheLevel = pParse.iCacheLevel; )
+ int iCacheLevel = pParse.iCacheLevel;
+ //VVA_ONLY( int iCacheLevel = pParse.iCacheLevel; )
#endif
- Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) && pExpr.x.pList != null );
- Debug.Assert( ( pExpr.x.pList.nExpr % 2 ) == 0 );
- Debug.Assert( pExpr.x.pList.nExpr > 0 );
- pEList = pExpr.x.pList;
- aListelem = pEList.a;
- nExpr = pEList.nExpr;
- endLabel = sqlite3VdbeMakeLabel( v );
- if ( ( pX = pExpr.pLeft ) != null )
- {
- cacheX = pX;
- testcase( pX.op == TK_COLUMN );
- testcase( pX.op == TK_REGISTER );
- cacheX.iTable = sqlite3ExprCodeTemp( pParse, pX, ref regFree1 );
- testcase( regFree1 == 0 );
- cacheX.op = TK_REGISTER;
- opCompare.op = TK_EQ;
- opCompare.pLeft = cacheX;
- pTest = opCompare;
- /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
- ** The value in regFree1 might get SCopy-ed into the file result.
- ** So make sure that the regFree1 register is not reused for other
- ** purposes and possibly overwritten. */
- regFree1 = 0;
- }
- for ( i = 0; i < nExpr; i = i + 2 )
- {
- sqlite3ExprCachePush( pParse );
- if ( pX != null )
- {
- Debug.Assert( pTest != null );
- opCompare.pRight = aListelem[i].pExpr;
- }
- else
- {
- pTest = aListelem[i].pExpr;
- }
- nextCase = sqlite3VdbeMakeLabel( v );
- testcase( pTest.op == TK_COLUMN );
- sqlite3ExprIfFalse( pParse, pTest, nextCase, SQLITE_JUMPIFNULL );
- testcase( aListelem[i + 1].pExpr.op == TK_COLUMN );
- testcase( aListelem[i + 1].pExpr.op == TK_REGISTER );
- sqlite3ExprCode( pParse, aListelem[i + 1].pExpr, target );
- sqlite3VdbeAddOp2( v, OP_Goto, 0, endLabel );
- sqlite3ExprCachePop( pParse, 1 );
- sqlite3VdbeResolveLabel( v, nextCase );
- }
- if ( pExpr.pRight != null )
- {
- sqlite3ExprCachePush( pParse );
- sqlite3ExprCode( pParse, pExpr.pRight, target );
- sqlite3ExprCachePop( pParse, 1 );
- }
- else
- {
- sqlite3VdbeAddOp2( v, OP_Null, 0, target );
- }
+ Debug.Assert(!ExprHasProperty(pExpr, EP_xIsSelect) && pExpr.x.pList != null);
+ Debug.Assert((pExpr.x.pList.nExpr % 2) == 0);
+ Debug.Assert(pExpr.x.pList.nExpr > 0);
+ pEList = pExpr.x.pList;
+ aListelem = pEList.a;
+ nExpr = pEList.nExpr;
+ endLabel = sqlite3VdbeMakeLabel(v);
+ if ((pX = pExpr.pLeft) != null) {
+ cacheX = pX;
+ testcase(pX.op == TK_COLUMN);
+ testcase(pX.op == TK_REGISTER);
+ cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, ref regFree1);
+ testcase(regFree1 == 0);
+ cacheX.op = TK_REGISTER;
+ opCompare.op = TK_EQ;
+ opCompare.pLeft = cacheX;
+ pTest = opCompare;
+ /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
+ ** The value in regFree1 might get SCopy-ed into the file result.
+ ** So make sure that the regFree1 register is not reused for other
+ ** purposes and possibly overwritten. */
+ regFree1 = 0;
+ }
+ for (i = 0; i < nExpr; i = i + 2) {
+ sqlite3ExprCachePush(pParse);
+ if (pX != null) {
+ Debug.Assert(pTest != null);
+ opCompare.pRight = aListelem[i].pExpr;
+ } else {
+ pTest = aListelem[i].pExpr;
+ }
+ nextCase = sqlite3VdbeMakeLabel(v);
+ testcase(pTest.op == TK_COLUMN);
+ sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
+ testcase(aListelem[i + 1].pExpr.op == TK_COLUMN);
+ testcase(aListelem[i + 1].pExpr.op == TK_REGISTER);
+ sqlite3ExprCode(pParse, aListelem[i + 1].pExpr, target);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
+ sqlite3ExprCachePop(pParse, 1);
+ sqlite3VdbeResolveLabel(v, nextCase);
+ }
+ if (pExpr.pRight != null) {
+ sqlite3ExprCachePush(pParse);
+ sqlite3ExprCode(pParse, pExpr.pRight, target);
+ sqlite3ExprCachePop(pParse, 1);
+ } else {
+ sqlite3VdbeAddOp2(v, OP_Null, 0, target);
+ }
#if !NDEBUG
- Debug.Assert( /* db.mallocFailed != 0 || */ pParse.nErr > 0
- || pParse.iCacheLevel == iCacheLevel );
+ Debug.Assert( /* db.mallocFailed != 0 || */ pParse.nErr > 0
+ || pParse.iCacheLevel == iCacheLevel);
#endif
- sqlite3VdbeResolveLabel( v, endLabel );
- break;
- }
+ sqlite3VdbeResolveLabel(v, endLabel);
+ break;
+ }
#if !SQLITE_OMIT_TRIGGER
- case TK_RAISE:
- {
- Debug.Assert( pExpr.affinity == OE_Rollback
- || pExpr.affinity == OE_Abort
- || pExpr.affinity == OE_Fail
- || pExpr.affinity == OE_Ignore
- );
- if ( null == pParse.pTriggerTab )
- {
- sqlite3ErrorMsg( pParse,
- "RAISE() may only be used within a trigger-program" );
- return 0;
- }
- if ( pExpr.affinity == OE_Abort )
- {
- sqlite3MayAbort( pParse );
- }
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- if ( pExpr.affinity == OE_Ignore )
- {
- sqlite3VdbeAddOp4(
- v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr.u.zToken, 0 );
- }
- else
- {
- sqlite3HaltConstraint( pParse, pExpr.affinity, pExpr.u.zToken, 0 );
- }
+ case TK_RAISE: {
+ Debug.Assert(pExpr.affinity == OE_Rollback
+ || pExpr.affinity == OE_Abort
+ || pExpr.affinity == OE_Fail
+ || pExpr.affinity == OE_Ignore
+ );
+ if (null == pParse.pTriggerTab) {
+ sqlite3ErrorMsg(pParse,
+ "RAISE() may only be used within a trigger-program");
+ return 0;
+ }
+ if (pExpr.affinity == OE_Abort) {
+ sqlite3MayAbort(pParse);
+ }
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ if (pExpr.affinity == OE_Ignore) {
+ sqlite3VdbeAddOp4(
+ v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr.u.zToken, 0);
+ } else {
+ sqlite3HaltConstraint(pParse, pExpr.affinity, pExpr.u.zToken, 0);
+ }
- break;
- }
+ break;
+ }
#endif
- }
- sqlite3ReleaseTempReg( pParse, regFree1 );
- sqlite3ReleaseTempReg( pParse, regFree2 );
- return inReg;
- }
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
+ return inReg;
+ }
- /*
- ** Generate code to evaluate an expression and store the results
- ** into a register. Return the register number where the results
- ** are stored.
- **
- ** If the register is a temporary register that can be deallocated,
- ** then write its number into pReg. If the result register is not
- ** a temporary, then set pReg to zero.
- */
- static int sqlite3ExprCodeTemp( Parse pParse, Expr pExpr, ref int pReg )
- {
- int r1 = sqlite3GetTempReg( pParse );
- int r2 = sqlite3ExprCodeTarget( pParse, pExpr, r1 );
- if ( r2 == r1 )
- {
- pReg = r1;
- }
- else
- {
- sqlite3ReleaseTempReg( pParse, r1 );
- pReg = 0;
- }
- return r2;
- }
+ /*
+ ** Generate code to evaluate an expression and store the results
+ ** into a register. Return the register number where the results
+ ** are stored.
+ **
+ ** If the register is a temporary register that can be deallocated,
+ ** then write its number into pReg. If the result register is not
+ ** a temporary, then set pReg to zero.
+ */
+ static int sqlite3ExprCodeTemp(Parse pParse, Expr pExpr, ref int pReg) {
+ int r1 = sqlite3GetTempReg(pParse);
+ int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
+ if (r2 == r1) {
+ pReg = r1;
+ } else {
+ sqlite3ReleaseTempReg(pParse, r1);
+ pReg = 0;
+ }
+ return r2;
+ }
- /*
- ** Generate code that will evaluate expression pExpr and store the
- ** results in register target. The results are guaranteed to appear
- ** in register target.
- */
- static int sqlite3ExprCode( Parse pParse, Expr pExpr, int target )
- {
- int inReg;
-
- Debug.Assert( target > 0 && target <= pParse.nMem );
- if ( pExpr != null && pExpr.op == TK_REGISTER )
- {
- sqlite3VdbeAddOp2( pParse.pVdbe, OP_Copy, pExpr.iTable, target );
- }
- else
- {
- inReg = sqlite3ExprCodeTarget( pParse, pExpr, target );
- Debug.Assert( pParse.pVdbe != null /* || pParse.db.mallocFailed != 0 */ );
- if ( inReg != target && pParse.pVdbe != null )
- {
- sqlite3VdbeAddOp2( pParse.pVdbe, OP_SCopy, inReg, target );
+ /*
+ ** Generate code that will evaluate expression pExpr and store the
+ ** results in register target. The results are guaranteed to appear
+ ** in register target.
+ */
+ static int sqlite3ExprCode(Parse pParse, Expr pExpr, int target) {
+ int inReg;
+
+ Debug.Assert(target > 0 && target <= pParse.nMem);
+ if (pExpr != null && pExpr.op == TK_REGISTER) {
+ sqlite3VdbeAddOp2(pParse.pVdbe, OP_Copy, pExpr.iTable, target);
+ } else {
+ inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
+ Debug.Assert(pParse.pVdbe != null /* || pParse.db.mallocFailed != 0 */ );
+ if (inReg != target && pParse.pVdbe != null) {
+ sqlite3VdbeAddOp2(pParse.pVdbe, OP_SCopy, inReg, target);
+ }
+ }
+ return target;
}
- }
- return target;
- }
- /*
- ** Generate code that evalutes the given expression and puts the result
- ** in register target.
- **
- ** Also make a copy of the expression results into another "cache" register
- ** and modify the expression so that the next time it is evaluated,
- ** the result is a copy of the cache register.
- **
- ** This routine is used for expressions that are used multiple
- ** times. They are evaluated once and the results of the expression
- ** are reused.
- */
- static int sqlite3ExprCodeAndCache( Parse pParse, Expr pExpr, int target )
- {
- Vdbe v = pParse.pVdbe;
- int inReg;
- inReg = sqlite3ExprCode( pParse, pExpr, target );
- Debug.Assert( target > 0 );
- /* This routine is called for terms to INSERT or UPDATE. And the only
- ** other place where expressions can be converted into TK_REGISTER is
- ** in WHERE clause processing. So as currently implemented, there is
- ** no way for a TK_REGISTER to exist here. But it seems prudent to
- ** keep the ALWAYS() in case the conditions above change with future
- ** modifications or enhancements. */
- if ( ALWAYS( pExpr.op != TK_REGISTER ) )
- {
- int iMem;
- iMem = ++pParse.nMem;
- sqlite3VdbeAddOp2( v, OP_Copy, inReg, iMem );
- pExpr.iTable = iMem;
- pExpr.op2 = pExpr.op;
- pExpr.op = TK_REGISTER;
- }
- return inReg;
- }
+ /*
+ ** Generate code that evalutes the given expression and puts the result
+ ** in register target.
+ **
+ ** Also make a copy of the expression results into another "cache" register
+ ** and modify the expression so that the next time it is evaluated,
+ ** the result is a copy of the cache register.
+ **
+ ** This routine is used for expressions that are used multiple
+ ** times. They are evaluated once and the results of the expression
+ ** are reused.
+ */
+ static int sqlite3ExprCodeAndCache(Parse pParse, Expr pExpr, int target) {
+ Vdbe v = pParse.pVdbe;
+ int inReg;
+ inReg = sqlite3ExprCode(pParse, pExpr, target);
+ Debug.Assert(target > 0);
+ /* This routine is called for terms to INSERT or UPDATE. And the only
+ ** other place where expressions can be converted into TK_REGISTER is
+ ** in WHERE clause processing. So as currently implemented, there is
+ ** no way for a TK_REGISTER to exist here. But it seems prudent to
+ ** keep the ALWAYS() in case the conditions above change with future
+ ** modifications or enhancements. */
+ if (ALWAYS(pExpr.op != TK_REGISTER)) {
+ int iMem;
+ iMem = ++pParse.nMem;
+ sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
+ pExpr.iTable = iMem;
+ pExpr.op2 = pExpr.op;
+ pExpr.op = TK_REGISTER;
+ }
+ return inReg;
+ }
- /*
- ** Return TRUE if pExpr is an constant expression that is appropriate
- ** for factoring out of a loop. Appropriate expressions are:
- **
- ** * Any expression that evaluates to two or more opcodes.
- **
- ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
- ** or OP_Variable that does not need to be placed in a
- ** specific register.
- **
- ** There is no point in factoring out single-instruction constant
- ** expressions that need to be placed in a particular register.
- ** We could factor them out, but then we would end up adding an
- ** OP_SCopy instruction to move the value into the correct register
- ** later. We might as well just use the original instruction and
- ** avoid the OP_SCopy.
- */
- static int isAppropriateForFactoring( Expr p )
- {
- if ( sqlite3ExprIsConstantNotJoin( p ) == 0 )
- {
- return 0; /* Only constant expressions are appropriate for factoring */
- }
- if ( ( p.flags & EP_FixedDest ) == 0 )
- {
- return 1; /* Any constant without a fixed destination is appropriate */
- }
- while ( p.op == TK_UPLUS )
- p = p.pLeft;
- switch ( p.op )
- {
-#if !SQLITE_OMIT_BLOB_LITERAL
- case TK_BLOB:
-#endif
- case TK_VARIABLE:
- case TK_INTEGER:
- case TK_FLOAT:
- case TK_NULL:
- case TK_STRING:
- {
- testcase( p.op == TK_BLOB );
- testcase( p.op == TK_VARIABLE );
- testcase( p.op == TK_INTEGER );
- testcase( p.op == TK_FLOAT );
- testcase( p.op == TK_NULL );
- testcase( p.op == TK_STRING );
- /* Single-instruction constants with a fixed destination are
- ** better done in-line. If we factor them, they will just end
- ** up generating an OP_SCopy to move the value to the destination
- ** register. */
- return 0;
- }
- case TK_UMINUS:
- {
- if ( p.pLeft.op == TK_FLOAT || p.pLeft.op == TK_INTEGER )
- {
- return 0;
+ /*
+ ** Return TRUE if pExpr is an constant expression that is appropriate
+ ** for factoring out of a loop. Appropriate expressions are:
+ **
+ ** * Any expression that evaluates to two or more opcodes.
+ **
+ ** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
+ ** or OP_Variable that does not need to be placed in a
+ ** specific register.
+ **
+ ** There is no point in factoring out single-instruction constant
+ ** expressions that need to be placed in a particular register.
+ ** We could factor them out, but then we would end up adding an
+ ** OP_SCopy instruction to move the value into the correct register
+ ** later. We might as well just use the original instruction and
+ ** avoid the OP_SCopy.
+ */
+ static int isAppropriateForFactoring(Expr p) {
+ if (sqlite3ExprIsConstantNotJoin(p) == 0) {
+ return 0; /* Only constant expressions are appropriate for factoring */
+ }
+ if ((p.flags & EP_FixedDest) == 0) {
+ return 1; /* Any constant without a fixed destination is appropriate */
}
- break;
- }
- default:
- {
- break;
- }
- }
- return 1;
- }
+ while (p.op == TK_UPLUS)
+ p = p.pLeft;
+ switch (p.op) {
+#if !SQLITE_OMIT_BLOB_LITERAL
+ case TK_BLOB:
+#endif
+ case TK_VARIABLE:
+ case TK_INTEGER:
+ case TK_FLOAT:
+ case TK_NULL:
+ case TK_STRING: {
+ testcase(p.op == TK_BLOB);
+ testcase(p.op == TK_VARIABLE);
+ testcase(p.op == TK_INTEGER);
+ testcase(p.op == TK_FLOAT);
+ testcase(p.op == TK_NULL);
+ testcase(p.op == TK_STRING);
+ /* Single-instruction constants with a fixed destination are
+ ** better done in-line. If we factor them, they will just end
+ ** up generating an OP_SCopy to move the value to the destination
+ ** register. */
+ return 0;
+ }
+ case TK_UMINUS: {
+ if (p.pLeft.op == TK_FLOAT || p.pLeft.op == TK_INTEGER) {
+ return 0;
+ }
+ break;
+ }
+ default: {
+ break;
+ }
+ }
+ return 1;
+ }
- /*
- ** If pExpr is a constant expression that is appropriate for
- ** factoring out of a loop, then evaluate the expression
- ** into a register and convert the expression into a TK_REGISTER
- ** expression.
- */
- static int evalConstExpr( Walker pWalker, ref Expr pExpr )
- {
- Parse pParse = pWalker.pParse;
- switch ( pExpr.op )
- {
- case TK_IN:
- case TK_REGISTER:
- {
- return WRC_Prune;
- }
- case TK_FUNCTION:
- case TK_AGG_FUNCTION:
- case TK_CONST_FUNC:
- {
- /* The arguments to a function have a fixed destination.
- ** Mark them this way to avoid generated unneeded OP_SCopy
- ** instructions.
- */
- ExprList pList = pExpr.x.pList;
- Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) );
- if ( pList != null )
- {
- int i = pList.nExpr;
- ExprList_item pItem;//= pList.a;
- for ( ; i > 0; i-- )
- {//, pItem++){
- pItem = pList.a[pList.nExpr - i];
- if ( ALWAYS( pItem.pExpr != null ) )
- pItem.pExpr.flags |= EP_FixedDest;
- }
+ /*
+ ** If pExpr is a constant expression that is appropriate for
+ ** factoring out of a loop, then evaluate the expression
+ ** into a register and convert the expression into a TK_REGISTER
+ ** expression.
+ */
+ static int evalConstExpr(Walker pWalker, ref Expr pExpr) {
+ Parse pParse = pWalker.pParse;
+ switch (pExpr.op) {
+ case TK_IN:
+ case TK_REGISTER: {
+ return WRC_Prune;
+ }
+ case TK_FUNCTION:
+ case TK_AGG_FUNCTION:
+ case TK_CONST_FUNC: {
+ /* The arguments to a function have a fixed destination.
+ ** Mark them this way to avoid generated unneeded OP_SCopy
+ ** instructions.
+ */
+ ExprList pList = pExpr.x.pList;
+ Debug.Assert(!ExprHasProperty(pExpr, EP_xIsSelect));
+ if (pList != null) {
+ int i = pList.nExpr;
+ ExprList_item pItem;//= pList.a;
+ for (; i > 0; i--) {//, pItem++){
+ pItem = pList.a[pList.nExpr - i];
+ if (ALWAYS(pItem.pExpr != null))
+ pItem.pExpr.flags |= EP_FixedDest;
+ }
+ }
+ break;
+ }
}
- break;
- }
- }
- if ( isAppropriateForFactoring( pExpr ) != 0 )
- {
- int r1 = ++pParse.nMem;
- int r2;
- r2 = sqlite3ExprCodeTarget( pParse, pExpr, r1 );
- if ( NEVER( r1 != r2 ) )
- sqlite3ReleaseTempReg( pParse, r1 );
- pExpr.op2 = pExpr.op;
- pExpr.op = TK_REGISTER;
- pExpr.iTable = r2;
- return WRC_Prune;
- }
- return WRC_Continue;
- }
+ if (isAppropriateForFactoring(pExpr) != 0) {
+ int r1 = ++pParse.nMem;
+ int r2;
+ r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
+ if (NEVER(r1 != r2))
+ sqlite3ReleaseTempReg(pParse, r1);
+ pExpr.op2 = pExpr.op;
+ pExpr.op = TK_REGISTER;
+ pExpr.iTable = r2;
+ return WRC_Prune;
+ }
+ return WRC_Continue;
+ }
- /*
- ** Preevaluate constant subexpressions within pExpr and store the
- ** results in registers. Modify pExpr so that the constant subexpresions
- ** are TK_REGISTER opcodes that refer to the precomputed values.
- **
- ** This routine is a no-op if the jump to the cookie-check code has
- ** already occur. Since the cookie-check jump is generated prior to
- ** any other serious processing, this check ensures that there is no
- ** way to accidently bypass the constant initializations.
- **
- ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
- ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
- ** interface. This allows test logic to verify that the same answer is
- ** obtained for queries regardless of whether or not constants are
- ** precomputed into registers or if they are inserted in-line.
- */
- static void sqlite3ExprCodeConstants( Parse pParse, Expr pExpr )
- {
- Walker w;
- if ( pParse.cookieGoto != 0 )
- return;
- if ( ( pParse.db.flags & SQLITE_FactorOutConst ) != 0 )
- return;
- w = new Walker();
- w.xExprCallback = (dxExprCallback)evalConstExpr;
- w.xSelectCallback = null;
- w.pParse = pParse;
- sqlite3WalkExpr( w, ref pExpr );
- }
+ /*
+ ** Preevaluate constant subexpressions within pExpr and store the
+ ** results in registers. Modify pExpr so that the constant subexpresions
+ ** are TK_REGISTER opcodes that refer to the precomputed values.
+ **
+ ** This routine is a no-op if the jump to the cookie-check code has
+ ** already occur. Since the cookie-check jump is generated prior to
+ ** any other serious processing, this check ensures that there is no
+ ** way to accidently bypass the constant initializations.
+ **
+ ** This routine is also a no-op if the SQLITE_FactorOutConst optimization
+ ** is disabled via the sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS)
+ ** interface. This allows test logic to verify that the same answer is
+ ** obtained for queries regardless of whether or not constants are
+ ** precomputed into registers or if they are inserted in-line.
+ */
+ static void sqlite3ExprCodeConstants(Parse pParse, Expr pExpr) {
+ Walker w;
+ if (pParse.cookieGoto != 0)
+ return;
+ if ((pParse.db.flags & SQLITE_FactorOutConst) != 0)
+ return;
+ w = new Walker();
+ w.xExprCallback = (dxExprCallback)evalConstExpr;
+ w.xSelectCallback = null;
+ w.pParse = pParse;
+ sqlite3WalkExpr(w, ref pExpr);
+ }
- /*
- ** Generate code that pushes the value of every element of the given
- ** expression list into a sequence of registers beginning at target.
- **
- ** Return the number of elements evaluated.
- */
- static int sqlite3ExprCodeExprList(
- Parse pParse, /* Parsing context */
- ExprList pList, /* The expression list to be coded */
- int target, /* Where to write results */
- bool doHardCopy /* Make a hard copy of every element */
- )
- {
- ExprList_item pItem;
- int i, n;
- Debug.Assert( pList != null );
- Debug.Assert( target > 0 );
- Debug.Assert( pParse.pVdbe != null ); /* Never gets this far otherwise */
- n = pList.nExpr;
- for ( i = 0; i < n; i++ )// pItem++)
- {
- pItem = pList.a[i];
- Expr pExpr = pItem.pExpr;
- int inReg = sqlite3ExprCodeTarget( pParse, pExpr, target + i );
- if ( inReg != target + i )
- {
- sqlite3VdbeAddOp2( pParse.pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
- inReg, target + i );
+ /*
+ ** Generate code that pushes the value of every element of the given
+ ** expression list into a sequence of registers beginning at target.
+ **
+ ** Return the number of elements evaluated.
+ */
+ static int sqlite3ExprCodeExprList(
+ Parse pParse, /* Parsing context */
+ ExprList pList, /* The expression list to be coded */
+ int target, /* Where to write results */
+ bool doHardCopy /* Make a hard copy of every element */
+ ) {
+ ExprList_item pItem;
+ int i, n;
+ Debug.Assert(pList != null);
+ Debug.Assert(target > 0);
+ Debug.Assert(pParse.pVdbe != null); /* Never gets this far otherwise */
+ n = pList.nExpr;
+ for (i = 0; i < n; i++)// pItem++)
+ {
+ pItem = pList.a[i];
+ Expr pExpr = pItem.pExpr;
+ int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target + i);
+ if (inReg != target + i) {
+ sqlite3VdbeAddOp2(pParse.pVdbe, doHardCopy ? OP_Copy : OP_SCopy,
+ inReg, target + i);
+ }
+ }
+ return n;
}
- }
- return n;
- }
- /*
- ** Generate code for a BETWEEN operator.
- **
- ** x BETWEEN y AND z
- **
- ** The above is equivalent to
- **
- ** x>=y AND x<=z
- **
- ** Code it as such, taking care to do the common subexpression
- ** elementation of x.
- */
- static void exprCodeBetween(
- Parse pParse, /* Parsing and code generating context */
- Expr pExpr, /* The BETWEEN expression */
- int dest, /* Jump here if the jump is taken */
- int jumpIfTrue, /* Take the jump if the BETWEEN is true */
- int jumpIfNull /* Take the jump if the BETWEEN is NULL */
- )
- {
- Expr exprAnd = new Expr(); /* The AND operator in x>=y AND x<=z */
- Expr compLeft = new Expr(); /* The x>=y term */
- Expr compRight = new Expr(); /* The x<=z term */
- Expr exprX; /* The x subexpression */
- int regFree1 = 0; /* Temporary use register */
-
- Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) );
- exprX = pExpr.pLeft.Copy();
- exprAnd.op = TK_AND;
- exprAnd.pLeft = compLeft;
- exprAnd.pRight = compRight;
- compLeft.op = TK_GE;
- compLeft.pLeft = exprX;
- compLeft.pRight = pExpr.x.pList.a[0].pExpr;
- compRight.op = TK_LE;
- compRight.pLeft = exprX;
- compRight.pRight = pExpr.x.pList.a[1].pExpr;
- exprX.iTable = sqlite3ExprCodeTemp( pParse, exprX, ref regFree1 );
- exprX.op = TK_REGISTER;
- if ( jumpIfTrue != 0 )
- {
- sqlite3ExprIfTrue( pParse, exprAnd, dest, jumpIfNull );
- }
- else
- {
- sqlite3ExprIfFalse( pParse, exprAnd, dest, jumpIfNull );
- }
- sqlite3ReleaseTempReg( pParse, regFree1 );
-
- /* Ensure adequate test coverage */
- testcase( jumpIfTrue == 0 && jumpIfNull == 0 && regFree1 == 0 );
- testcase( jumpIfTrue == 0 && jumpIfNull == 0 && regFree1 != 0 );
- testcase( jumpIfTrue == 0 && jumpIfNull != 0 && regFree1 == 0 );
- testcase( jumpIfTrue == 0 && jumpIfNull != 0 && regFree1 != 0 );
- testcase( jumpIfTrue != 0 && jumpIfNull == 0 && regFree1 == 0 );
- testcase( jumpIfTrue != 0 && jumpIfNull == 0 && regFree1 != 0 );
- testcase( jumpIfTrue != 0 && jumpIfNull != 0 && regFree1 == 0 );
- testcase( jumpIfTrue != 0 && jumpIfNull != 0 && regFree1 != 0 );
- }
- /*
- ** Generate code for a boolean expression such that a jump is made
- ** to the label "dest" if the expression is true but execution
- ** continues straight thru if the expression is false.
- **
- ** If the expression evaluates to NULL (neither true nor false), then
- ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
- **
- ** This code depends on the fact that certain token values (ex: TK_EQ)
- ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
- ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
- ** the make process cause these values to align. Assert()s in the code
- ** below verify that the numbers are aligned correctly.
- */
- static void sqlite3ExprIfTrue( Parse pParse, Expr pExpr, int dest, int jumpIfNull )
- {
- Vdbe v = pParse.pVdbe;
- int op = 0;
- int regFree1 = 0;
- int regFree2 = 0;
- int r1 = 0, r2 = 0;
-
- Debug.Assert( jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0 );
- if ( NEVER( v == null ) )
- return; /* Existance of VDBE checked by caller */
- if ( NEVER( pExpr == null ) )
- return; /* No way this can happen */
- op = pExpr.op;
- switch ( op )
- {
- case TK_AND:
- {
- int d2 = sqlite3VdbeMakeLabel( v );
- testcase( jumpIfNull == 0 );
- sqlite3ExprCachePush( pParse );
- sqlite3ExprIfFalse( pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL );
- sqlite3ExprIfTrue( pParse, pExpr.pRight, dest, jumpIfNull );
- sqlite3VdbeResolveLabel( v, d2 );
- sqlite3ExprCachePop( pParse, 1 );
- break;
- }
- case TK_OR:
- {
- testcase( jumpIfNull == 0 );
- sqlite3ExprIfTrue( pParse, pExpr.pLeft, dest, jumpIfNull );
- sqlite3ExprIfTrue( pParse, pExpr.pRight, dest, jumpIfNull );
- break;
- }
- case TK_NOT:
- {
- testcase( jumpIfNull == 0 );
- sqlite3ExprIfFalse( pParse, pExpr.pLeft, dest, jumpIfNull );
- break;
- }
- case TK_LT:
- case TK_LE:
- case TK_GT:
- case TK_GE:
- case TK_NE:
- case TK_EQ:
- {
- Debug.Assert( TK_LT == OP_Lt );
- Debug.Assert( TK_LE == OP_Le );
- Debug.Assert( TK_GT == OP_Gt );
- Debug.Assert( TK_GE == OP_Ge );
- Debug.Assert( TK_EQ == OP_Eq );
- Debug.Assert( TK_NE == OP_Ne );
- testcase( op == TK_LT );
- testcase( op == TK_LE );
- testcase( op == TK_GT );
- testcase( op == TK_GE );
- testcase( op == TK_EQ );
- testcase( op == TK_NE );
- testcase( jumpIfNull == 0 );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op,
- r1, r2, dest, jumpIfNull );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_IS:
- case TK_ISNOT:
- {
- testcase( op == TK_IS );
- testcase( op == TK_ISNOT );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- op = ( op == TK_IS ) ? TK_EQ : TK_NE;
- codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op,
- r1, r2, dest, SQLITE_NULLEQ );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_ISNULL:
- case TK_NOTNULL:
- {
- Debug.Assert( TK_ISNULL == OP_IsNull );
- Debug.Assert( TK_NOTNULL == OP_NotNull );
- testcase( op == TK_ISNULL );
- testcase( op == TK_NOTNULL );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- sqlite3VdbeAddOp2( v, op, r1, dest );
- testcase( regFree1 == 0 );
- break;
- }
- case TK_BETWEEN:
- {
- testcase( jumpIfNull == 0 );
- exprCodeBetween( pParse, pExpr, dest, 1, jumpIfNull );
- break;
- }
+ /*
+ ** Generate code for a BETWEEN operator.
+ **
+ ** x BETWEEN y AND z
+ **
+ ** The above is equivalent to
+ **
+ ** x>=y AND x<=z
+ **
+ ** Code it as such, taking care to do the common subexpression
+ ** elementation of x.
+ */
+ static void exprCodeBetween(
+ Parse pParse, /* Parsing and code generating context */
+ Expr pExpr, /* The BETWEEN expression */
+ int dest, /* Jump here if the jump is taken */
+ int jumpIfTrue, /* Take the jump if the BETWEEN is true */
+ int jumpIfNull /* Take the jump if the BETWEEN is NULL */
+ ) {
+ Expr exprAnd = new Expr(); /* The AND operator in x>=y AND x<=z */
+ Expr compLeft = new Expr(); /* The x>=y term */
+ Expr compRight = new Expr(); /* The x<=z term */
+ Expr exprX; /* The x subexpression */
+ int regFree1 = 0; /* Temporary use register */
+
+ Debug.Assert(!ExprHasProperty(pExpr, EP_xIsSelect));
+ exprX = pExpr.pLeft.Copy();
+ exprAnd.op = TK_AND;
+ exprAnd.pLeft = compLeft;
+ exprAnd.pRight = compRight;
+ compLeft.op = TK_GE;
+ compLeft.pLeft = exprX;
+ compLeft.pRight = pExpr.x.pList.a[0].pExpr;
+ compRight.op = TK_LE;
+ compRight.pLeft = exprX;
+ compRight.pRight = pExpr.x.pList.a[1].pExpr;
+ exprX.iTable = sqlite3ExprCodeTemp(pParse, exprX, ref regFree1);
+ exprX.op = TK_REGISTER;
+ if (jumpIfTrue != 0) {
+ sqlite3ExprIfTrue(pParse, exprAnd, dest, jumpIfNull);
+ } else {
+ sqlite3ExprIfFalse(pParse, exprAnd, dest, jumpIfNull);
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+
+ /* Ensure adequate test coverage */
+ testcase(jumpIfTrue == 0 && jumpIfNull == 0 && regFree1 == 0);
+ testcase(jumpIfTrue == 0 && jumpIfNull == 0 && regFree1 != 0);
+ testcase(jumpIfTrue == 0 && jumpIfNull != 0 && regFree1 == 0);
+ testcase(jumpIfTrue == 0 && jumpIfNull != 0 && regFree1 != 0);
+ testcase(jumpIfTrue != 0 && jumpIfNull == 0 && regFree1 == 0);
+ testcase(jumpIfTrue != 0 && jumpIfNull == 0 && regFree1 != 0);
+ testcase(jumpIfTrue != 0 && jumpIfNull != 0 && regFree1 == 0);
+ testcase(jumpIfTrue != 0 && jumpIfNull != 0 && regFree1 != 0);
+ }
+ /*
+ ** Generate code for a boolean expression such that a jump is made
+ ** to the label "dest" if the expression is true but execution
+ ** continues straight thru if the expression is false.
+ **
+ ** If the expression evaluates to NULL (neither true nor false), then
+ ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
+ **
+ ** This code depends on the fact that certain token values (ex: TK_EQ)
+ ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
+ ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
+ ** the make process cause these values to align. Assert()s in the code
+ ** below verify that the numbers are aligned correctly.
+ */
+ static void sqlite3ExprIfTrue(Parse pParse, Expr pExpr, int dest, int jumpIfNull) {
+ Vdbe v = pParse.pVdbe;
+ int op = 0;
+ int regFree1 = 0;
+ int regFree2 = 0;
+ int r1 = 0, r2 = 0;
+
+ Debug.Assert(jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0);
+ if (NEVER(v == null))
+ return; /* Existance of VDBE checked by caller */
+ if (NEVER(pExpr == null))
+ return; /* No way this can happen */
+ op = pExpr.op;
+ switch (op) {
+ case TK_AND: {
+ int d2 = sqlite3VdbeMakeLabel(v);
+ testcase(jumpIfNull == 0);
+ sqlite3ExprCachePush(pParse);
+ sqlite3ExprIfFalse(pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL);
+ sqlite3ExprIfTrue(pParse, pExpr.pRight, dest, jumpIfNull);
+ sqlite3VdbeResolveLabel(v, d2);
+ sqlite3ExprCachePop(pParse, 1);
+ break;
+ }
+ case TK_OR: {
+ testcase(jumpIfNull == 0);
+ sqlite3ExprIfTrue(pParse, pExpr.pLeft, dest, jumpIfNull);
+ sqlite3ExprIfTrue(pParse, pExpr.pRight, dest, jumpIfNull);
+ break;
+ }
+ case TK_NOT: {
+ testcase(jumpIfNull == 0);
+ sqlite3ExprIfFalse(pParse, pExpr.pLeft, dest, jumpIfNull);
+ break;
+ }
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_NE:
+ case TK_EQ: {
+ Debug.Assert(TK_LT == OP_Lt);
+ Debug.Assert(TK_LE == OP_Le);
+ Debug.Assert(TK_GT == OP_Gt);
+ Debug.Assert(TK_GE == OP_Ge);
+ Debug.Assert(TK_EQ == OP_Eq);
+ Debug.Assert(TK_NE == OP_Ne);
+ testcase(op == TK_LT);
+ testcase(op == TK_LE);
+ testcase(op == TK_GT);
+ testcase(op == TK_GE);
+ testcase(op == TK_EQ);
+ testcase(op == TK_NE);
+ testcase(jumpIfNull == 0);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ codeCompare(pParse, pExpr.pLeft, pExpr.pRight, op,
+ r1, r2, dest, jumpIfNull);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_IS:
+ case TK_ISNOT: {
+ testcase(op == TK_IS);
+ testcase(op == TK_ISNOT);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ op = (op == TK_IS) ? TK_EQ : TK_NE;
+ codeCompare(pParse, pExpr.pLeft, pExpr.pRight, op,
+ r1, r2, dest, SQLITE_NULLEQ);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_ISNULL:
+ case TK_NOTNULL: {
+ Debug.Assert(TK_ISNULL == OP_IsNull);
+ Debug.Assert(TK_NOTNULL == OP_NotNull);
+ testcase(op == TK_ISNULL);
+ testcase(op == TK_NOTNULL);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ sqlite3VdbeAddOp2(v, op, r1, dest);
+ testcase(regFree1 == 0);
+ break;
+ }
+ case TK_BETWEEN: {
+ testcase(jumpIfNull == 0);
+ exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
+ break;
+ }
#if SQLITE_OMIT_SUBQUERY
case TK_IN:
{
@@ -3850,151 +3445,141 @@ static void sqlite3ExprIfTrue( Parse pParse, Expr pExpr, int dest, int jumpIfNul
break;
}
#endif
- default:
- {
- r1 = sqlite3ExprCodeTemp( pParse, pExpr, ref regFree1 );
- sqlite3VdbeAddOp3( v, OP_If, r1, dest, jumpIfNull != 0 ? 1 : 0 );
- testcase( regFree1 == 0 );
- testcase( jumpIfNull == 0 );
- break;
- }
- }
- sqlite3ReleaseTempReg( pParse, regFree1 );
- sqlite3ReleaseTempReg( pParse, regFree2 );
- }
+ default: {
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr, ref regFree1);
+ sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull != 0 ? 1 : 0);
+ testcase(regFree1 == 0);
+ testcase(jumpIfNull == 0);
+ break;
+ }
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
+ }
- /*
- ** Generate code for a boolean expression such that a jump is made
- ** to the label "dest" if the expression is false but execution
- ** continues straight thru if the expression is true.
- **
- ** If the expression evaluates to NULL (neither true nor false) then
- ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
- ** is 0.
- */
- static void sqlite3ExprIfFalse( Parse pParse, Expr pExpr, int dest, int jumpIfNull )
- {
- Vdbe v = pParse.pVdbe;
- int op = 0;
- int regFree1 = 0;
- int regFree2 = 0;
- int r1 = 0, r2 = 0;
-
- Debug.Assert( jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0 );
- if ( NEVER( v == null ) )
- return; /* Existance of VDBE checked by caller */
- if ( pExpr == null )
- return;
-
- /* The value of pExpr.op and op are related as follows:
- **
- ** pExpr.op op
- ** --------- ----------
- ** TK_ISNULL OP_NotNull
- ** TK_NOTNULL OP_IsNull
- ** TK_NE OP_Eq
- ** TK_EQ OP_Ne
- ** TK_GT OP_Le
- ** TK_LE OP_Gt
- ** TK_GE OP_Lt
- ** TK_LT OP_Ge
- **
- ** For other values of pExpr.op, op is undefined and unused.
- ** The value of TK_ and OP_ constants are arranged such that we
- ** can compute the mapping above using the following expression.
- ** Assert()s verify that the computation is correct.
- */
- op = ( ( pExpr.op + ( TK_ISNULL & 1 ) ) ^ 1 ) - ( TK_ISNULL & 1 );
-
- /* Verify correct alignment of TK_ and OP_ constants
- */
- Debug.Assert( pExpr.op != TK_ISNULL || op == OP_NotNull );
- Debug.Assert( pExpr.op != TK_NOTNULL || op == OP_IsNull );
- Debug.Assert( pExpr.op != TK_NE || op == OP_Eq );
- Debug.Assert( pExpr.op != TK_EQ || op == OP_Ne );
- Debug.Assert( pExpr.op != TK_LT || op == OP_Ge );
- Debug.Assert( pExpr.op != TK_LE || op == OP_Gt );
- Debug.Assert( pExpr.op != TK_GT || op == OP_Le );
- Debug.Assert( pExpr.op != TK_GE || op == OP_Lt );
-
- switch ( pExpr.op )
- {
- case TK_AND:
- {
- testcase( jumpIfNull == 0 );
- sqlite3ExprIfFalse( pParse, pExpr.pLeft, dest, jumpIfNull );
- sqlite3ExprIfFalse( pParse, pExpr.pRight, dest, jumpIfNull );
- break;
- }
- case TK_OR:
- {
- int d2 = sqlite3VdbeMakeLabel( v );
- testcase( jumpIfNull == 0 );
- sqlite3ExprCachePush( pParse );
- sqlite3ExprIfTrue( pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL );
- sqlite3ExprIfFalse( pParse, pExpr.pRight, dest, jumpIfNull );
- sqlite3VdbeResolveLabel( v, d2 );
- sqlite3ExprCachePop( pParse, 1 );
- break;
- }
- case TK_NOT:
- {
- testcase( jumpIfNull == 0 );
- sqlite3ExprIfTrue( pParse, pExpr.pLeft, dest, jumpIfNull );
- break;
- }
- case TK_LT:
- case TK_LE:
- case TK_GT:
- case TK_GE:
- case TK_NE:
- case TK_EQ:
- {
- testcase( op == TK_LT );
- testcase( op == TK_LE );
- testcase( op == TK_GT );
- testcase( op == TK_GE );
- testcase( op == TK_EQ );
- testcase( op == TK_NE );
- testcase( jumpIfNull == 0 );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op,
- r1, r2, dest, jumpIfNull );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_IS:
- case TK_ISNOT:
- {
- testcase( pExpr.op == TK_IS );
- testcase( pExpr.op == TK_ISNOT );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- r2 = sqlite3ExprCodeTemp( pParse, pExpr.pRight, ref regFree2 );
- op = ( pExpr.op == TK_IS ) ? TK_NE : TK_EQ;
- codeCompare( pParse, pExpr.pLeft, pExpr.pRight, op,
- r1, r2, dest, SQLITE_NULLEQ );
- testcase( regFree1 == 0 );
- testcase( regFree2 == 0 );
- break;
- }
- case TK_ISNULL:
- case TK_NOTNULL:
- {
- testcase( op == TK_ISNULL );
- testcase( op == TK_NOTNULL );
- r1 = sqlite3ExprCodeTemp( pParse, pExpr.pLeft, ref regFree1 );
- sqlite3VdbeAddOp2( v, op, r1, dest );
- testcase( regFree1 == 0 );
- break;
- }
- case TK_BETWEEN:
- {
- testcase( jumpIfNull == 0 );
- exprCodeBetween( pParse, pExpr, dest, 0, jumpIfNull );
- break;
- }
+ /*
+ ** Generate code for a boolean expression such that a jump is made
+ ** to the label "dest" if the expression is false but execution
+ ** continues straight thru if the expression is true.
+ **
+ ** If the expression evaluates to NULL (neither true nor false) then
+ ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
+ ** is 0.
+ */
+ static void sqlite3ExprIfFalse(Parse pParse, Expr pExpr, int dest, int jumpIfNull) {
+ Vdbe v = pParse.pVdbe;
+ int op = 0;
+ int regFree1 = 0;
+ int regFree2 = 0;
+ int r1 = 0, r2 = 0;
+
+ Debug.Assert(jumpIfNull == SQLITE_JUMPIFNULL || jumpIfNull == 0);
+ if (NEVER(v == null))
+ return; /* Existance of VDBE checked by caller */
+ if (pExpr == null)
+ return;
+
+ /* The value of pExpr.op and op are related as follows:
+ **
+ ** pExpr.op op
+ ** --------- ----------
+ ** TK_ISNULL OP_NotNull
+ ** TK_NOTNULL OP_IsNull
+ ** TK_NE OP_Eq
+ ** TK_EQ OP_Ne
+ ** TK_GT OP_Le
+ ** TK_LE OP_Gt
+ ** TK_GE OP_Lt
+ ** TK_LT OP_Ge
+ **
+ ** For other values of pExpr.op, op is undefined and unused.
+ ** The value of TK_ and OP_ constants are arranged such that we
+ ** can compute the mapping above using the following expression.
+ ** Assert()s verify that the computation is correct.
+ */
+ op = ((pExpr.op + (TK_ISNULL & 1)) ^ 1) - (TK_ISNULL & 1);
+
+ /* Verify correct alignment of TK_ and OP_ constants
+ */
+ Debug.Assert(pExpr.op != TK_ISNULL || op == OP_NotNull);
+ Debug.Assert(pExpr.op != TK_NOTNULL || op == OP_IsNull);
+ Debug.Assert(pExpr.op != TK_NE || op == OP_Eq);
+ Debug.Assert(pExpr.op != TK_EQ || op == OP_Ne);
+ Debug.Assert(pExpr.op != TK_LT || op == OP_Ge);
+ Debug.Assert(pExpr.op != TK_LE || op == OP_Gt);
+ Debug.Assert(pExpr.op != TK_GT || op == OP_Le);
+ Debug.Assert(pExpr.op != TK_GE || op == OP_Lt);
+
+ switch (pExpr.op) {
+ case TK_AND: {
+ testcase(jumpIfNull == 0);
+ sqlite3ExprIfFalse(pParse, pExpr.pLeft, dest, jumpIfNull);
+ sqlite3ExprIfFalse(pParse, pExpr.pRight, dest, jumpIfNull);
+ break;
+ }
+ case TK_OR: {
+ int d2 = sqlite3VdbeMakeLabel(v);
+ testcase(jumpIfNull == 0);
+ sqlite3ExprCachePush(pParse);
+ sqlite3ExprIfTrue(pParse, pExpr.pLeft, d2, jumpIfNull ^ SQLITE_JUMPIFNULL);
+ sqlite3ExprIfFalse(pParse, pExpr.pRight, dest, jumpIfNull);
+ sqlite3VdbeResolveLabel(v, d2);
+ sqlite3ExprCachePop(pParse, 1);
+ break;
+ }
+ case TK_NOT: {
+ testcase(jumpIfNull == 0);
+ sqlite3ExprIfTrue(pParse, pExpr.pLeft, dest, jumpIfNull);
+ break;
+ }
+ case TK_LT:
+ case TK_LE:
+ case TK_GT:
+ case TK_GE:
+ case TK_NE:
+ case TK_EQ: {
+ testcase(op == TK_LT);
+ testcase(op == TK_LE);
+ testcase(op == TK_GT);
+ testcase(op == TK_GE);
+ testcase(op == TK_EQ);
+ testcase(op == TK_NE);
+ testcase(jumpIfNull == 0);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ codeCompare(pParse, pExpr.pLeft, pExpr.pRight, op,
+ r1, r2, dest, jumpIfNull);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_IS:
+ case TK_ISNOT: {
+ testcase(pExpr.op == TK_IS);
+ testcase(pExpr.op == TK_ISNOT);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ r2 = sqlite3ExprCodeTemp(pParse, pExpr.pRight, ref regFree2);
+ op = (pExpr.op == TK_IS) ? TK_NE : TK_EQ;
+ codeCompare(pParse, pExpr.pLeft, pExpr.pRight, op,
+ r1, r2, dest, SQLITE_NULLEQ);
+ testcase(regFree1 == 0);
+ testcase(regFree2 == 0);
+ break;
+ }
+ case TK_ISNULL:
+ case TK_NOTNULL: {
+ testcase(op == TK_ISNULL);
+ testcase(op == TK_NOTNULL);
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr.pLeft, ref regFree1);
+ sqlite3VdbeAddOp2(v, op, r1, dest);
+ testcase(regFree1 == 0);
+ break;
+ }
+ case TK_BETWEEN: {
+ testcase(jumpIfNull == 0);
+ exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
+ break;
+ }
#if SQLITE_OMIT_SUBQUERY
case TK_IN:
{
@@ -4011,432 +3596,379 @@ static void sqlite3ExprIfFalse( Parse pParse, Expr pExpr, int dest, int jumpIfNu
break;
}
#endif
- default:
- {
- r1 = sqlite3ExprCodeTemp( pParse, pExpr, ref regFree1 );
- sqlite3VdbeAddOp3( v, OP_IfNot, r1, dest, jumpIfNull != 0 ? 1 : 0 );
- testcase( regFree1 == 0 );
- testcase( jumpIfNull == 0 );
- break;
- }
- }
- sqlite3ReleaseTempReg( pParse, regFree1 );
- sqlite3ReleaseTempReg( pParse, regFree2 );
- }
-
- /*
- ** Do a deep comparison of two expression trees. Return 0 if the two
- ** expressions are completely identical. Return 1 if they differ only
- ** by a COLLATE operator at the top level. Return 2 if there are differences
- ** other than the top-level COLLATE operator.
- **
- ** Sometimes this routine will return 2 even if the two expressions
- ** really are equivalent. If we cannot prove that the expressions are
- ** identical, we return 2 just to be safe. So if this routine
- ** returns 2, then you do not really know for certain if the two
- ** expressions are the same. But if you get a 0 or 1 return, then you
- ** can be sure the expressions are the same. In the places where
- ** this routine is used, it does not hurt to get an extra 2 - that
- ** just might result in some slightly slower code. But returning
- ** an incorrect 0 or 1 could lead to a malfunction.
- */
- static int sqlite3ExprCompare( Expr pA, Expr pB )
- {
- if ( pA == null || pB == null )
- {
- return pB == pA ? 0 : 2;
- }
- Debug.Assert( !ExprHasAnyProperty( pA, EP_TokenOnly | EP_Reduced ) );
- Debug.Assert( !ExprHasAnyProperty( pB, EP_TokenOnly | EP_Reduced ) );
- if ( ExprHasProperty( pA, EP_xIsSelect ) || ExprHasProperty( pB, EP_xIsSelect ) )
- {
- return 2;
- }
- if ( ( pA.flags & EP_Distinct ) != ( pB.flags & EP_Distinct ) )
- return 2;
- if ( pA.op != pB.op )
- return 2;
- if ( sqlite3ExprCompare( pA.pLeft, pB.pLeft ) != 0 )
- return 2;
- if ( sqlite3ExprCompare( pA.pRight, pB.pRight ) != 0 )
- return 2;
- if ( sqlite3ExprListCompare( pA.x.pList, pB.x.pList ) != 0 )
- return 2;
- if ( pA.iTable != pB.iTable || pA.iColumn != pB.iColumn )
- return 2;
- if ( ExprHasProperty( pA, EP_IntValue ) )
- {
- if ( !ExprHasProperty( pB, EP_IntValue ) || pA.u.iValue != pB.u.iValue )
- {
- return 2;
+ default: {
+ r1 = sqlite3ExprCodeTemp(pParse, pExpr, ref regFree1);
+ sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull != 0 ? 1 : 0);
+ testcase(regFree1 == 0);
+ testcase(jumpIfNull == 0);
+ break;
+ }
+ }
+ sqlite3ReleaseTempReg(pParse, regFree1);
+ sqlite3ReleaseTempReg(pParse, regFree2);
}
- }
- else if ( pA.op != TK_COLUMN && pA.u.zToken != null )
- {
- if ( ExprHasProperty( pB, EP_IntValue ) || NEVER( pB.u.zToken == null ) )
- return 2;
- if ( !pA.u.zToken.Equals( pB.u.zToken ,StringComparison.OrdinalIgnoreCase ) )
- {
- return 2;
+
+ /*
+ ** Do a deep comparison of two expression trees. Return 0 if the two
+ ** expressions are completely identical. Return 1 if they differ only
+ ** by a COLLATE operator at the top level. Return 2 if there are differences
+ ** other than the top-level COLLATE operator.
+ **
+ ** Sometimes this routine will return 2 even if the two expressions
+ ** really are equivalent. If we cannot prove that the expressions are
+ ** identical, we return 2 just to be safe. So if this routine
+ ** returns 2, then you do not really know for certain if the two
+ ** expressions are the same. But if you get a 0 or 1 return, then you
+ ** can be sure the expressions are the same. In the places where
+ ** this routine is used, it does not hurt to get an extra 2 - that
+ ** just might result in some slightly slower code. But returning
+ ** an incorrect 0 or 1 could lead to a malfunction.
+ */
+ static int sqlite3ExprCompare(Expr pA, Expr pB) {
+ if (pA == null || pB == null) {
+ return pB == pA ? 0 : 2;
+ }
+ Debug.Assert(!ExprHasAnyProperty(pA, EP_TokenOnly | EP_Reduced));
+ Debug.Assert(!ExprHasAnyProperty(pB, EP_TokenOnly | EP_Reduced));
+ if (ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect)) {
+ return 2;
+ }
+ if ((pA.flags & EP_Distinct) != (pB.flags & EP_Distinct))
+ return 2;
+ if (pA.op != pB.op)
+ return 2;
+ if (sqlite3ExprCompare(pA.pLeft, pB.pLeft) != 0)
+ return 2;
+ if (sqlite3ExprCompare(pA.pRight, pB.pRight) != 0)
+ return 2;
+ if (sqlite3ExprListCompare(pA.x.pList, pB.x.pList) != 0)
+ return 2;
+ if (pA.iTable != pB.iTable || pA.iColumn != pB.iColumn)
+ return 2;
+ if (ExprHasProperty(pA, EP_IntValue)) {
+ if (!ExprHasProperty(pB, EP_IntValue) || pA.u.iValue != pB.u.iValue) {
+ return 2;
+ }
+ } else if (pA.op != TK_COLUMN && pA.u.zToken != null) {
+ if (ExprHasProperty(pB, EP_IntValue) || NEVER(pB.u.zToken == null))
+ return 2;
+ if (!pA.u.zToken.Equals(pB.u.zToken, StringComparison.OrdinalIgnoreCase)) {
+ return 2;
+ }
+ }
+ if ((pA.flags & EP_ExpCollate) != (pB.flags & EP_ExpCollate))
+ return 1;
+ if ((pA.flags & EP_ExpCollate) != 0 && pA.pColl != pB.pColl)
+ return 2;
+ return 0;
}
- }
- if ( ( pA.flags & EP_ExpCollate ) != ( pB.flags & EP_ExpCollate ) )
- return 1;
- if ( ( pA.flags & EP_ExpCollate ) != 0 && pA.pColl != pB.pColl )
- return 2;
- return 0;
- }
- /*
- ** Compare two ExprList objects. Return 0 if they are identical and
- ** non-zero if they differ in any way.
- **
- ** This routine might return non-zero for equivalent ExprLists. The
- ** only consequence will be disabled optimizations. But this routine
- ** must never return 0 if the two ExprList objects are different, or
- ** a malfunction will result.
- **
- ** Two NULL pointers are considered to be the same. But a NULL pointer
- ** always differs from a non-NULL pointer.
- */
- static int sqlite3ExprListCompare( ExprList pA, ExprList pB )
- {
- int i;
- if ( pA == null && pB == null )
- return 0;
- if ( pA == null || pB == null )
- return 1;
- if ( pA.nExpr != pB.nExpr )
- return 1;
- for ( i = 0; i < pA.nExpr; i++ )
- {
- Expr pExprA = pA.a[i].pExpr;
- Expr pExprB = pB.a[i].pExpr;
- if ( pA.a[i].sortOrder != pB.a[i].sortOrder )
- return 1;
- if ( sqlite3ExprCompare( pExprA, pExprB ) != 0 )
- return 1;
- }
- return 0;
- }
+ /*
+ ** Compare two ExprList objects. Return 0 if they are identical and
+ ** non-zero if they differ in any way.
+ **
+ ** This routine might return non-zero for equivalent ExprLists. The
+ ** only consequence will be disabled optimizations. But this routine
+ ** must never return 0 if the two ExprList objects are different, or
+ ** a malfunction will result.
+ **
+ ** Two NULL pointers are considered to be the same. But a NULL pointer
+ ** always differs from a non-NULL pointer.
+ */
+ static int sqlite3ExprListCompare(ExprList pA, ExprList pB) {
+ int i;
+ if (pA == null && pB == null)
+ return 0;
+ if (pA == null || pB == null)
+ return 1;
+ if (pA.nExpr != pB.nExpr)
+ return 1;
+ for (i = 0; i < pA.nExpr; i++) {
+ Expr pExprA = pA.a[i].pExpr;
+ Expr pExprB = pB.a[i].pExpr;
+ if (pA.a[i].sortOrder != pB.a[i].sortOrder)
+ return 1;
+ if (sqlite3ExprCompare(pExprA, pExprB) != 0)
+ return 1;
+ }
+ return 0;
+ }
- /*
- ** Add a new element to the pAggInfo.aCol[] array. Return the index of
- ** the new element. Return a negative number if malloc fails.
- */
- static int addAggInfoColumn( sqlite3 db, AggInfo pInfo )
- {
- int i = 0;
- pInfo.aCol = sqlite3ArrayAllocate(
- db,
- pInfo.aCol,
- -1,//sizeof(pInfo.aCol[0]),
- 3,
- ref pInfo.nColumn,
- ref pInfo.nColumnAlloc,
- ref i
- );
- return i;
- }
+ /*
+ ** Add a new element to the pAggInfo.aCol[] array. Return the index of
+ ** the new element. Return a negative number if malloc fails.
+ */
+ static int addAggInfoColumn(sqlite3 db, AggInfo pInfo) {
+ int i = 0;
+ pInfo.aCol = sqlite3ArrayAllocate(
+ db,
+ pInfo.aCol,
+ -1,//sizeof(pInfo.aCol[0]),
+ 3,
+ ref pInfo.nColumn,
+ ref pInfo.nColumnAlloc,
+ ref i
+ );
+ return i;
+ }
- /*
- ** Add a new element to the pAggInfo.aFunc[] array. Return the index of
- ** the new element. Return a negative number if malloc fails.
- */
- static int addAggInfoFunc( sqlite3 db, AggInfo pInfo )
- {
- int i = 0;
- pInfo.aFunc = sqlite3ArrayAllocate(
- db,
- pInfo.aFunc,
- -1,//sizeof(pInfo.aFunc[0]),
- 3,
- ref pInfo.nFunc,
- ref pInfo.nFuncAlloc,
- ref i
- );
- return i;
- }
+ /*
+ ** Add a new element to the pAggInfo.aFunc[] array. Return the index of
+ ** the new element. Return a negative number if malloc fails.
+ */
+ static int addAggInfoFunc(sqlite3 db, AggInfo pInfo) {
+ int i = 0;
+ pInfo.aFunc = sqlite3ArrayAllocate(
+ db,
+ pInfo.aFunc,
+ -1,//sizeof(pInfo.aFunc[0]),
+ 3,
+ ref pInfo.nFunc,
+ ref pInfo.nFuncAlloc,
+ ref i
+ );
+ return i;
+ }
- /*
- ** This is the xExprCallback for a tree walker. It is used to
- ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
- ** for additional information.
- */
- static int analyzeAggregate( Walker pWalker, ref Expr pExpr )
- {
- int i;
- NameContext pNC = pWalker.u.pNC;
- Parse pParse = pNC.pParse;
- SrcList pSrcList = pNC.pSrcList;
- AggInfo pAggInfo = pNC.pAggInfo;
-
- switch ( pExpr.op )
- {
- case TK_AGG_COLUMN:
- case TK_COLUMN:
- {
- testcase( pExpr.op == TK_AGG_COLUMN );
- testcase( pExpr.op == TK_COLUMN );
- /* Check to see if the column is in one of the tables in the FROM
- ** clause of the aggregate query */
- if ( ALWAYS( pSrcList != null ) )
- {
- SrcList_item pItem;// = pSrcList.a;
- for ( i = 0; i < pSrcList.nSrc; i++ )
- {//, pItem++){
- pItem = pSrcList.a[i];
- AggInfo_col pCol;
- Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) );
- if ( pExpr.iTable == pItem.iCursor )
- {
- /* If we reach this point, it means that pExpr refers to a table
- ** that is in the FROM clause of the aggregate query.
- **
- ** Make an entry for the column in pAggInfo.aCol[] if there
- ** is not an entry there already.
- */
- int k;
- //pCol = pAggInfo.aCol;
- for ( k = 0; k < pAggInfo.nColumn; k++ )
- {//, pCol++){
- pCol = pAggInfo.aCol[k];
- if ( pCol.iTable == pExpr.iTable &&
- pCol.iColumn == pExpr.iColumn )
- {
- break;
- }
- }
- if ( ( k >= pAggInfo.nColumn )
- && ( k = addAggInfoColumn( pParse.db, pAggInfo ) ) >= 0
- )
- {
- pCol = pAggInfo.aCol[k];
- pCol.pTab = pExpr.pTab;
- pCol.iTable = pExpr.iTable;
- pCol.iColumn = pExpr.iColumn;
- pCol.iMem = ++pParse.nMem;
- pCol.iSorterColumn = -1;
- pCol.pExpr = pExpr;
- if ( pAggInfo.pGroupBy != null )
- {
- int j, n;
- ExprList pGB = pAggInfo.pGroupBy;
- ExprList_item pTerm;// = pGB.a;
- n = pGB.nExpr;
- for ( j = 0; j < n; j++ )
- {//, pTerm++){
- pTerm = pGB.a[j];
- Expr pE = pTerm.pExpr;
- if ( pE.op == TK_COLUMN && pE.iTable == pExpr.iTable &&
- pE.iColumn == pExpr.iColumn )
- {
- pCol.iSorterColumn = j;
- break;
+ /*
+ ** This is the xExprCallback for a tree walker. It is used to
+ ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
+ ** for additional information.
+ */
+ static int analyzeAggregate(Walker pWalker, ref Expr pExpr) {
+ int i;
+ NameContext pNC = pWalker.u.pNC;
+ Parse pParse = pNC.pParse;
+ SrcList pSrcList = pNC.pSrcList;
+ AggInfo pAggInfo = pNC.pAggInfo;
+
+ switch (pExpr.op) {
+ case TK_AGG_COLUMN:
+ case TK_COLUMN: {
+ testcase(pExpr.op == TK_AGG_COLUMN);
+ testcase(pExpr.op == TK_COLUMN);
+ /* Check to see if the column is in one of the tables in the FROM
+ ** clause of the aggregate query */
+ if (ALWAYS(pSrcList != null)) {
+ SrcList_item pItem;// = pSrcList.a;
+ for (i = 0; i < pSrcList.nSrc; i++) {//, pItem++){
+ pItem = pSrcList.a[i];
+ AggInfo_col pCol;
+ Debug.Assert(!ExprHasAnyProperty(pExpr, EP_TokenOnly | EP_Reduced));
+ if (pExpr.iTable == pItem.iCursor) {
+ /* If we reach this point, it means that pExpr refers to a table
+ ** that is in the FROM clause of the aggregate query.
+ **
+ ** Make an entry for the column in pAggInfo.aCol[] if there
+ ** is not an entry there already.
+ */
+ int k;
+ //pCol = pAggInfo.aCol;
+ for (k = 0; k < pAggInfo.nColumn; k++) {//, pCol++){
+ pCol = pAggInfo.aCol[k];
+ if (pCol.iTable == pExpr.iTable &&
+ pCol.iColumn == pExpr.iColumn) {
+ break;
+ }
+ }
+ if ((k >= pAggInfo.nColumn)
+ && (k = addAggInfoColumn(pParse.db, pAggInfo)) >= 0
+ ) {
+ pCol = pAggInfo.aCol[k];
+ pCol.pTab = pExpr.pTab;
+ pCol.iTable = pExpr.iTable;
+ pCol.iColumn = pExpr.iColumn;
+ pCol.iMem = ++pParse.nMem;
+ pCol.iSorterColumn = -1;
+ pCol.pExpr = pExpr;
+ if (pAggInfo.pGroupBy != null) {
+ int j, n;
+ ExprList pGB = pAggInfo.pGroupBy;
+ ExprList_item pTerm;// = pGB.a;
+ n = pGB.nExpr;
+ for (j = 0; j < n; j++) {//, pTerm++){
+ pTerm = pGB.a[j];
+ Expr pE = pTerm.pExpr;
+ if (pE.op == TK_COLUMN && pE.iTable == pExpr.iTable &&
+ pE.iColumn == pExpr.iColumn) {
+ pCol.iSorterColumn = j;
+ break;
+ }
+ }
+ }
+ if (pCol.iSorterColumn < 0) {
+ pCol.iSorterColumn = pAggInfo.nSortingColumn++;
+ }
+ }
+ /* There is now an entry for pExpr in pAggInfo.aCol[] (either
+ ** because it was there before or because we just created it).
+ ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
+ ** pAggInfo.aCol[] entry.
+ */
+ ExprSetIrreducible(pExpr);
+ pExpr.pAggInfo = pAggInfo;
+ pExpr.op = TK_AGG_COLUMN;
+ pExpr.iAgg = (short)k;
+ break;
+ } /* endif pExpr.iTable==pItem.iCursor */
+ } /* end loop over pSrcList */
}
- }
+ return WRC_Prune;
}
- if ( pCol.iSorterColumn < 0 )
- {
- pCol.iSorterColumn = pAggInfo.nSortingColumn++;
+ case TK_AGG_FUNCTION: {
+ /* The pNC.nDepth==0 test causes aggregate functions in subqueries
+ ** to be ignored */
+ if (pNC.nDepth == 0) {
+ /* Check to see if pExpr is a duplicate of another aggregate
+ ** function that is already in the pAggInfo structure
+ */
+ AggInfo_func pItem;// = pAggInfo.aFunc;
+ for (i = 0; i < pAggInfo.nFunc; i++) {//, pItem++){
+ pItem = pAggInfo.aFunc[i];
+ if (sqlite3ExprCompare(pItem.pExpr, pExpr) == 0) {
+ break;
+ }
+ }
+ if (i >= pAggInfo.nFunc) {
+ /* pExpr is original. Make a new entry in pAggInfo.aFunc[]
+ */
+ u8 enc = pParse.db.aDbStatic[0].pSchema.enc;// ENC(pParse.db);
+ i = addAggInfoFunc(pParse.db, pAggInfo);
+ if (i >= 0) {
+ Debug.Assert(!ExprHasProperty(pExpr, EP_xIsSelect));
+ pItem = pAggInfo.aFunc[i];
+ pItem.pExpr = pExpr;
+ pItem.iMem = ++pParse.nMem;
+ Debug.Assert(!ExprHasProperty(pExpr, EP_IntValue));
+ pItem.pFunc = sqlite3FindFunction(pParse.db,
+ pExpr.u.zToken, sqlite3Strlen30(pExpr.u.zToken),
+ pExpr.x.pList != null ? pExpr.x.pList.nExpr : 0, enc, 0);
+ if ((pExpr.flags & EP_Distinct) != 0) {
+ pItem.iDistinct = pParse.nTab++;
+ } else {
+ pItem.iDistinct = -1;
+ }
+ }
+ }
+ /* Make pExpr point to the appropriate pAggInfo.aFunc[] entry
+ */
+ Debug.Assert(!ExprHasAnyProperty(pExpr, EP_TokenOnly | EP_Reduced));
+ ExprSetIrreducible(pExpr);
+ pExpr.iAgg = (short)i;
+ pExpr.pAggInfo = pAggInfo;
+ return WRC_Prune;
+ }
+ break;
}
- }
- /* There is now an entry for pExpr in pAggInfo.aCol[] (either
- ** because it was there before or because we just created it).
- ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
- ** pAggInfo.aCol[] entry.
- */
- ExprSetIrreducible( pExpr );
- pExpr.pAggInfo = pAggInfo;
- pExpr.op = TK_AGG_COLUMN;
- pExpr.iAgg = (short)k;
- break;
- } /* endif pExpr.iTable==pItem.iCursor */
- } /* end loop over pSrcList */
- }
- return WRC_Prune;
- }
- case TK_AGG_FUNCTION:
- {
- /* The pNC.nDepth==0 test causes aggregate functions in subqueries
- ** to be ignored */
- if ( pNC.nDepth == 0 )
- {
- /* Check to see if pExpr is a duplicate of another aggregate
- ** function that is already in the pAggInfo structure
- */
- AggInfo_func pItem;// = pAggInfo.aFunc;
- for ( i = 0; i < pAggInfo.nFunc; i++ )
- {//, pItem++){
- pItem = pAggInfo.aFunc[i];
- if ( sqlite3ExprCompare( pItem.pExpr, pExpr ) == 0 )
- {
- break;
- }
- }
- if ( i >= pAggInfo.nFunc )
- {
- /* pExpr is original. Make a new entry in pAggInfo.aFunc[]
- */
- u8 enc = pParse.db.aDbStatic[0].pSchema.enc;// ENC(pParse.db);
- i = addAggInfoFunc( pParse.db, pAggInfo );
- if ( i >= 0 )
- {
- Debug.Assert( !ExprHasProperty( pExpr, EP_xIsSelect ) );
- pItem = pAggInfo.aFunc[i];
- pItem.pExpr = pExpr;
- pItem.iMem = ++pParse.nMem;
- Debug.Assert( !ExprHasProperty( pExpr, EP_IntValue ) );
- pItem.pFunc = sqlite3FindFunction( pParse.db,
- pExpr.u.zToken, sqlite3Strlen30( pExpr.u.zToken ),
- pExpr.x.pList != null ? pExpr.x.pList.nExpr : 0, enc, 0 );
- if ( ( pExpr.flags & EP_Distinct ) != 0 )
- {
- pItem.iDistinct = pParse.nTab++;
- }
- else
- {
- pItem.iDistinct = -1;
- }
- }
- }
- /* Make pExpr point to the appropriate pAggInfo.aFunc[] entry
- */
- Debug.Assert( !ExprHasAnyProperty( pExpr, EP_TokenOnly | EP_Reduced ) );
- ExprSetIrreducible( pExpr );
- pExpr.iAgg = (short)i;
- pExpr.pAggInfo = pAggInfo;
- return WRC_Prune;
}
- break;
- }
- }
- return WRC_Continue;
- }
+ return WRC_Continue;
+ }
- static int analyzeAggregatesInSelect( Walker pWalker, Select pSelect )
- {
- NameContext pNC = pWalker.u.pNC;
- if ( pNC.nDepth == 0 )
- {
- pNC.nDepth++;
- sqlite3WalkSelect( pWalker, pSelect );
- pNC.nDepth--;
- return WRC_Prune;
- }
- else
- {
- return WRC_Continue;
- }
- }
+ static int analyzeAggregatesInSelect(Walker pWalker, Select pSelect) {
+ NameContext pNC = pWalker.u.pNC;
+ if (pNC.nDepth == 0) {
+ pNC.nDepth++;
+ sqlite3WalkSelect(pWalker, pSelect);
+ pNC.nDepth--;
+ return WRC_Prune;
+ } else {
+ return WRC_Continue;
+ }
+ }
- /*
- ** Analyze the given expression looking for aggregate functions and
- ** for variables that need to be added to the pParse.aAgg[] array.
- ** Make additional entries to the pParse.aAgg[] array as necessary.
- **
- ** This routine should only be called after the expression has been
- ** analyzed by sqlite3ResolveExprNames().
- */
- static void sqlite3ExprAnalyzeAggregates( NameContext pNC, ref Expr pExpr )
- {
- Walker w = new Walker();
- w.xExprCallback = (dxExprCallback)analyzeAggregate;
- w.xSelectCallback = (dxSelectCallback)analyzeAggregatesInSelect;
- w.u.pNC = pNC;
- Debug.Assert( pNC.pSrcList != null );
- sqlite3WalkExpr( w, ref pExpr );
- }
+ /*
+ ** Analyze the given expression looking for aggregate functions and
+ ** for variables that need to be added to the pParse.aAgg[] array.
+ ** Make additional entries to the pParse.aAgg[] array as necessary.
+ **
+ ** This routine should only be called after the expression has been
+ ** analyzed by sqlite3ResolveExprNames().
+ */
+ static void sqlite3ExprAnalyzeAggregates(NameContext pNC, ref Expr pExpr) {
+ Walker w = new Walker();
+ w.xExprCallback = (dxExprCallback)analyzeAggregate;
+ w.xSelectCallback = (dxSelectCallback)analyzeAggregatesInSelect;
+ w.u.pNC = pNC;
+ Debug.Assert(pNC.pSrcList != null);
+ sqlite3WalkExpr(w, ref pExpr);
+ }
- /*
- ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
- ** expression list. Return the number of errors.
- **
- ** If an error is found, the analysis is cut short.
- */
- static void sqlite3ExprAnalyzeAggList( NameContext pNC, ExprList pList )
- {
- ExprList_item pItem;
- int i;
- if ( pList != null )
- {
- for ( i = 0; i < pList.nExpr; i++ )//, pItem++)
- {
- pItem = pList.a[i];
- sqlite3ExprAnalyzeAggregates( pNC, ref pItem.pExpr );
+ /*
+ ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
+ ** expression list. Return the number of errors.
+ **
+ ** If an error is found, the analysis is cut short.
+ */
+ static void sqlite3ExprAnalyzeAggList(NameContext pNC, ExprList pList) {
+ ExprList_item pItem;
+ int i;
+ if (pList != null) {
+ for (i = 0; i < pList.nExpr; i++)//, pItem++)
+ {
+ pItem = pList.a[i];
+ sqlite3ExprAnalyzeAggregates(pNC, ref pItem.pExpr);
+ }
+ }
}
- }
- }
- /*
- ** Allocate a single new register for use to hold some intermediate result.
- */
- static int sqlite3GetTempReg( Parse pParse )
- {
- if ( pParse.nTempReg == 0 )
- {
- return ++pParse.nMem;
- }
- return pParse.aTempReg[--pParse.nTempReg];
- }
+ /*
+ ** Allocate a single new register for use to hold some intermediate result.
+ */
+ static int sqlite3GetTempReg(Parse pParse) {
+ if (pParse.nTempReg == 0) {
+ return ++pParse.nMem;
+ }
+ return pParse.aTempReg[--pParse.nTempReg];
+ }
- /*
- ** Deallocate a register, making available for reuse for some other
- ** purpose.
- **
- ** If a register is currently being used by the column cache, then
- ** the dallocation is deferred until the column cache line that uses
- ** the register becomes stale.
- */
- static void sqlite3ReleaseTempReg( Parse pParse, int iReg )
- {
- if ( iReg != 0 && pParse.nTempReg < ArraySize( pParse.aTempReg ) )
- {
- int i;
- yColCache p;
- for ( i = 0; i < SQLITE_N_COLCACHE; i++ )//p=pParse.aColCache... p++)
- {
- p = pParse.aColCache[i];
- if ( p.iReg == iReg )
- {
- p.tempReg = 1;
- return;
- }
+ /*
+ ** Deallocate a register, making available for reuse for some other
+ ** purpose.
+ **
+ ** If a register is currently being used by the column cache, then
+ ** the dallocation is deferred until the column cache line that uses
+ ** the register becomes stale.
+ */
+ static void sqlite3ReleaseTempReg(Parse pParse, int iReg) {
+ if (iReg != 0 && pParse.nTempReg < ArraySize(pParse.aTempReg)) {
+ int i;
+ yColCache p;
+ for (i = 0; i < SQLITE_N_COLCACHE; i++)//p=pParse.aColCache... p++)
+ {
+ p = pParse.aColCache[i];
+ if (p.iReg == iReg) {
+ p.tempReg = 1;
+ return;
+ }
+ }
+ pParse.aTempReg[pParse.nTempReg++] = iReg;
+ }
}
- pParse.aTempReg[pParse.nTempReg++] = iReg;
- }
- }
- /*
- ** Allocate or deallocate a block of nReg consecutive registers
- */
- static int sqlite3GetTempRange( Parse pParse, int nReg )
- {
- int i, n;
- i = pParse.iRangeReg;
- n = pParse.nRangeReg;
- if ( nReg <= n )
- {
- //Debug.Assert( 1 == usedAsColumnCache( pParse, i, i + n - 1 ) );
- pParse.iRangeReg += nReg;
- pParse.nRangeReg -= nReg;
- }
- else
- {
- i = pParse.nMem + 1;
- pParse.nMem += nReg;
- }
- return i;
- }
- static void sqlite3ReleaseTempRange( Parse pParse, int iReg, int nReg )
- {
- sqlite3ExprCacheRemove( pParse, iReg, nReg );
- if ( nReg > pParse.nRangeReg )
- {
- pParse.nRangeReg = nReg;
- pParse.iRangeReg = iReg;
- }
+ /*
+ ** Allocate or deallocate a block of nReg consecutive registers
+ */
+ static int sqlite3GetTempRange(Parse pParse, int nReg) {
+ int i, n;
+ i = pParse.iRangeReg;
+ n = pParse.nRangeReg;
+ if (nReg <= n) {
+ //Debug.Assert( 1 == usedAsColumnCache( pParse, i, i + n - 1 ) );
+ pParse.iRangeReg += nReg;
+ pParse.nRangeReg -= nReg;
+ } else {
+ i = pParse.nMem + 1;
+ pParse.nMem += nReg;
+ }
+ return i;
+ }
+ static void sqlite3ReleaseTempRange(Parse pParse, int iReg, int nReg) {
+ sqlite3ExprCacheRemove(pParse, iReg, nReg);
+ if (nReg > pParse.nRangeReg) {
+ pParse.nRangeReg = nReg;
+ pParse.iRangeReg = iReg;
+ }
+ }
}
- }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/fault_c.cs b/Src/IronPython.SQLite/c#sqlite/fault_c.cs
index d94636d7e..2faf4fa51 100644
--- a/Src/IronPython.SQLite/c#sqlite/fault_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/fault_c.cs
@@ -1,116 +1,104 @@
-using System;
-using System.Diagnostics;
-
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
- ** 2008 Jan 22
- **
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
- **
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
- *************************************************************************
- **
- ** This file contains code to support the concept of "benign"
- ** malloc failures (when the xMalloc() or xRealloc() method of the
- ** sqlite3_mem_methods structure fails to allocate a block of memory
- ** and returns 0).
- **
- ** Most malloc failures are non-benign. After they occur, SQLite
- ** abandons the current operation and returns an error code (usually
- ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
- ** fatal. For example, if a malloc fails while resizing a hash table, this
- ** is completely recoverable simply by not carrying out the resize. The
- ** hash table will continue to function normally. So a malloc failure
- ** during a hash table resize is a benign fault.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
- **
- ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
- **
- *************************************************************************
- */
- //#include "sqliteInt.h"
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ ** 2008 Jan 22
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ *************************************************************************
+ **
+ ** This file contains code to support the concept of "benign"
+ ** malloc failures (when the xMalloc() or xRealloc() method of the
+ ** sqlite3_mem_methods structure fails to allocate a block of memory
+ ** and returns 0).
+ **
+ ** Most malloc failures are non-benign. After they occur, SQLite
+ ** abandons the current operation and returns an error code (usually
+ ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
+ ** fatal. For example, if a malloc fails while resizing a hash table, this
+ ** is completely recoverable simply by not carrying out the resize. The
+ ** hash table will continue to function normally. So a malloc failure
+ ** during a hash table resize is a benign fault.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
+ **
+ *************************************************************************
+ */
+ //#include "sqliteInt.h"
#if !SQLITE_OMIT_BUILTIN_TEST
- /*
-** Global variables.
-*/
- //typedef struct BenignMallocHooks BenignMallocHooks;
- public struct BenignMallocHooks//
- {
- public void_function xBenignBegin;//void (*xBenignBegin)(void);
- public void_function xBenignEnd; //void (*xBenignEnd)(void);
- public BenignMallocHooks( void_function xBenignBegin, void_function xBenignEnd )
- {
- this.xBenignBegin = xBenignBegin;
- this.xBenignEnd = xBenignEnd;
- }
- }
- static BenignMallocHooks sqlite3Hooks = new BenignMallocHooks( null, null );
-
- /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
- ** structure. If writable static data is unsupported on the target,
- ** we have to locate the state vector at run-time. In the more common
- ** case where writable static data is supported, wsdHooks can refer directly
- ** to the "sqlite3Hooks" state vector declared above.
+ /*
+ ** Global variables.
*/
+ //typedef struct BenignMallocHooks BenignMallocHooks;
+ public struct BenignMallocHooks//
+ {
+ public void_function xBenignBegin;//void (*xBenignBegin)(void);
+ public void_function xBenignEnd; //void (*xBenignEnd)(void);
+ public BenignMallocHooks(void_function xBenignBegin, void_function xBenignEnd) {
+ this.xBenignBegin = xBenignBegin;
+ this.xBenignEnd = xBenignEnd;
+ }
+ }
+ static BenignMallocHooks sqlite3Hooks = new BenignMallocHooks(null, null);
+
+ /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
+ ** structure. If writable static data is unsupported on the target,
+ ** we have to locate the state vector at run-time. In the more common
+ ** case where writable static data is supported, wsdHooks can refer directly
+ ** to the "sqlite3Hooks" state vector declared above.
+ */
#if SQLITE_OMIT_WSD
//# define wsdHooksInit \
BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
//# define wsdHooks x[0]
#else
- //# define wsdHooksInit
- static void wsdHooksInit()
- {
- }
- //# define wsdHooks sqlite3Hooks
- static BenignMallocHooks wsdHooks = sqlite3Hooks;
+ //# define wsdHooksInit
+ static void wsdHooksInit() {
+ }
+ //# define wsdHooks sqlite3Hooks
+ static BenignMallocHooks wsdHooks = sqlite3Hooks;
#endif
- /*
-** Register hooks to call when sqlite3BeginBenignMalloc() and
-** sqlite3EndBenignMalloc() are called, respectively.
-*/
- static void sqlite3BenignMallocHooks(
- void_function xBenignBegin, //void (*xBenignBegin)(void),
- void_function xBenignEnd //void (*xBenignEnd)(void)
- )
- {
- wsdHooksInit();
- wsdHooks.xBenignBegin = xBenignBegin;
- wsdHooks.xBenignEnd = xBenignEnd;
- }
-
- /*
- ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
- ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
- ** indicates that subsequent malloc failures are non-benign.
+ /*
+ ** Register hooks to call when sqlite3BeginBenignMalloc() and
+ ** sqlite3EndBenignMalloc() are called, respectively.
*/
- static void sqlite3BeginBenignMalloc()
- {
- wsdHooksInit();
- if ( wsdHooks.xBenignBegin != null )
- {
- wsdHooks.xBenignBegin();
- }
- }
- static void sqlite3EndBenignMalloc()
- {
- wsdHooksInit();
- if ( wsdHooks.xBenignEnd != null )
- {
- wsdHooks.xBenignEnd();
- }
- }
+ static void sqlite3BenignMallocHooks(
+ void_function xBenignBegin, //void (*xBenignBegin)(void),
+ void_function xBenignEnd //void (*xBenignEnd)(void)
+ ) {
+ wsdHooksInit();
+ wsdHooks.xBenignBegin = xBenignBegin;
+ wsdHooks.xBenignEnd = xBenignEnd;
+ }
+
+ /*
+ ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
+ ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
+ ** indicates that subsequent malloc failures are non-benign.
+ */
+ static void sqlite3BeginBenignMalloc() {
+ wsdHooksInit();
+ if (wsdHooks.xBenignBegin != null) {
+ wsdHooks.xBenignBegin();
+ }
+ }
+ static void sqlite3EndBenignMalloc() {
+ wsdHooksInit();
+ if (wsdHooks.xBenignEnd != null) {
+ wsdHooks.xBenignEnd();
+ }
+ }
#endif //* SQLITE_OMIT_BUILTIN_TEST */
- }
+ }
}
diff --git a/Src/IronPython.SQLite/c#sqlite/fkey_c.cs b/Src/IronPython.SQLite/c#sqlite/fkey_c.cs
index fc3a967ec..76c124190 100644
--- a/Src/IronPython.SQLite/c#sqlite/fkey_c.cs
+++ b/Src/IronPython.SQLite/c#sqlite/fkey_c.cs
@@ -1,854 +1,786 @@
using System;
using System.Diagnostics;
-using System.Text;
-using Bitmask = System.UInt64;
-using u8 = System.Byte;
using u32 = System.UInt32;
+using u8 = System.Byte;
+
+namespace Community.CsharpSqlite {
+ public partial class Sqlite3 {
+ /*
+ **
+ ** The author disclaims copyright to this source code. In place of
+ ** a legal notice, here is a blessing:
+ **
+ ** May you do good and not evil.
+ ** May you find forgiveness for yourself and forgive others.
+ ** May you share freely, never taking more than you give.
+ **
+ *************************************************************************
+ ** This file contains code used by the compiler to add foreign key
+ ** support to compiled SQL statements.
+ *************************************************************************
+ ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
+ ** C#-SQLite is an independent reimplementation of the SQLite software library
+ **
+ ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ **
+ ************************************************************************* */
+ //#include "sqliteInt.h"
-namespace Community.CsharpSqlite
-{
- public partial class Sqlite3
- {
- /*
+#if !SQLITE_OMIT_FOREIGN_KEY
+#if !SQLITE_OMIT_TRIGGER
+
+ /*
+ ** Deferred and Immediate FKs
+ ** --------------------------
**
- ** The author disclaims copyright to this source code. In place of
- ** a legal notice, here is a blessing:
+ ** Foreign keys in SQLite come in two flavours: deferred and immediate.
+ ** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
+ ** is returned and the current statement transaction rolled back. If a
+ ** deferred foreign key constraint is violated, no action is taken
+ ** immediately. However if the application attempts to commit the
+ ** transaction before fixing the constraint violation, the attempt fails.
**
- ** May you do good and not evil.
- ** May you find forgiveness for yourself and forgive others.
- ** May you share freely, never taking more than you give.
+ ** Deferred constraints are implemented using a simple counter associated
+ ** with the database handle. The counter is set to zero each time a
+ ** database transaction is opened. Each time a statement is executed
+ ** that causes a foreign key violation, the counter is incremented. Each
+ ** time a statement is executed that removes an existing violation from
+ ** the database, the counter is decremented. When the transaction is
+ ** committed, the commit fails if the current value of the counter is
+ ** greater than zero. This scheme has two big drawbacks:
**
- *************************************************************************
- ** This file contains code used by the compiler to add foreign key
- ** support to compiled SQL statements.
- *************************************************************************
- ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
- ** C#-SQLite is an independent reimplementation of the SQLite software library
+ ** * When a commit fails due to a deferred foreign key constraint,
+ ** there is no way to tell which foreign constraint is not satisfied,
+ ** or which row it is not satisfied for.
**
- ** SQLITE_SOURCE_ID: 2011-06-23 19:49:22 4374b7e83ea0a3fbc3691f9c0c936272862f32f2
+ ** * If the database contains foreign key violations when the
+ ** transaction is opened, this may cause the mechanism to malfunction.
**
- ************************************************************************* */
- //#include "sqliteInt.h"
-
-#if !SQLITE_OMIT_FOREIGN_KEY
-#if !SQLITE_OMIT_TRIGGER
-
- /*
-** Deferred and Immediate FKs
-** --------------------------
-**
-** Foreign keys in SQLite come in two flavours: deferred and immediate.
-** If an immediate foreign key constraint is violated, SQLITE_CONSTRAINT
-** is returned and the current statement transaction rolled back. If a
-** deferred foreign key constraint is violated, no action is taken
-** immediately. However if the application attempts to commit the
-** transaction before fixing the constraint violation, the attempt fails.
-**
-** Deferred constraints are implemented using a simple counter associated
-** with the database handle. The counter is set to zero each time a
-** database transaction is opened. Each time a statement is executed
-** that causes a foreign key violation, the counter is incremented. Each
-** time a statement is executed that removes an existing violation from
-** the database, the counter is decremented. When the transaction is
-** committed, the commit fails if the current value of the counter is
-** greater than zero. This scheme has two big drawbacks:
-**
-** * When a commit fails due to a deferred foreign key constraint,
-** there is no way to tell which foreign constraint is not satisfied,
-** or which row it is not satisfied for.
-**
-** * If the database contains foreign key violations when the
-** transaction is opened, this may cause the mechanism to malfunction.
-**
-** Despite these problems, this approach is adopted as it seems simpler
-** than the alternatives.
-**
-** INSERT operations:
-**
-** I.1) For each FK for which the table is the child table, search
-** the parent table for a match. If none is found increment the
-** constraint counter.
-**
-** I.2) For each FK for which the table is the parent table,
-** search the child table for rows that correspond to the new
-** row in the parent table. Decrement the counter for each row
-** found (as the constraint is now satisfied).
-**
-** DELETE operations:
-**
-** D.1) For each FK for which the table is the child table,
-** search the parent table for a row that corresponds to the
-** deleted row in the child table. If such a row is not found,
-** decrement the counter.
-**
-** D.2) For each FK for which the table is the parent table, search
-** the child table for rows that correspond to the deleted row
-** in the parent table. For each found increment the counter.
-**
-** UPDATE operations:
-**
-** An UPDATE command requires that all 4 steps above are taken, but only
-** for FK constraints for which the affected columns are actually
-** modified (values must be compared at runtime).
-**
-** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
-** This simplifies the implementation a bit.
-**
-** For the purposes of immediate FK constraints, the OR REPLACE conflict
-** resolution is considered to delete rows before the new row is inserted.
-** If a delete caused by OR REPLACE violates an FK constraint, an exception
-** is thrown, even if the FK constraint would be satisfied after the new
-** row is inserted.
-**
-** Immediate constraints are usually handled similarly. The only difference
-** is that the counter used is stored as part of each individual statement
-** object (struct Vdbe). If, after the statement has run, its immediate
-** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
-** and the statement transaction is rolled back. An exception is an INSERT
-** statement that inserts a single row only (no triggers). In this case,
-** instead of using a counter, an exception is thrown immediately if the
-** INSERT violates a foreign key constraint. This is necessary as such
-** an INSERT does not open a statement transaction.
-**
-** TODO: How should dropping a table be handled? How should renaming a
-** table be handled?
-**
-**
-** Query API Notes
-** ---------------
-**
-** Before coding an UPDATE or DELETE row operation, the code-generator
-** for those two operations needs to know whether or not the operation
-** requires any FK processing and, if so, which columns of the original
-** row are required by the FK processing VDBE code (i.e. if FKs were
-** implemented using triggers, which of the old.* columns would be
-** accessed). No information is required by the code-generator before
-** coding an INSERT operation. The functions used by the UPDATE/DELETE
-** generation code to query for this information are:
-**
-** sqlite3FkRequired() - Test to see if FK processing is required.
-** sqlite3FkOldmask() - Query for the set of required old.* columns.
-**
-**
-** Externally accessible module functions
-** --------------------------------------
-**
-** sqlite3FkCheck() - Check for foreign key violations.
-** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
-** sqlite3FkDelete() - Delete an FKey structure.
-*/
-
- /*
- ** VDBE Calling Convention
- ** -----------------------
+ ** Despite these problems, this approach is adopted as it seems simpler
+ ** than the alternatives.
**
- ** Example:
+ ** INSERT operations:
**
- ** For the following INSERT statement:
+ ** I.1) For each FK for which the table is the child table, search
+ ** the parent table for a match. If none is found increment the
+ ** constraint counter.
**
- ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
- ** INSERT INTO t1 VALUES(1, 2, 3.1);
+ ** I.2) For each FK for which the table is the parent table,
+ ** search the child table for rows that correspond to the new
+ ** row in the parent table. Decrement the counter for each row
+ ** found (as the constraint is now satisfied).
**
- ** Register (x): 2 (type integer)
- ** Register (x+1): 1 (type integer)
- ** Register (x+2): NULL (type NULL)
- ** Register (x+3): 3.1 (type real)
- */
-
- /*
- ** A foreign key constraint requires that the key columns in the parent
- ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
- ** Given that pParent is the parent table for foreign key constraint pFKey,
- ** search the schema a unique index on the parent key columns.
+ ** DELETE operations:
**
- ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
- ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
- ** is set to point to the unique index.
- **
- ** If the parent key consists of a single column (the foreign key constraint
- ** is not a composite foreign key), refput variable *paiCol is set to NULL.
- ** Otherwise, it is set to point to an allocated array of size N, where
- ** N is the number of columns in the parent key. The first element of the
- ** array is the index of the child table column that is mapped by the FK
- ** constraint to the parent table column stored in the left-most column
- ** of index *ppIdx. The second element of the array is the index of the
- ** child table column that corresponds to the second left-most column of
- ** *ppIdx, and so on.
+ ** D.1) For each FK for which the table is the child table,
+ ** search the parent table for a row that corresponds to the
+ ** deleted row in the child table. If such a row is not found,
+ ** decrement the counter.
**
- ** If the required index cannot be found, either because:
+ ** D.2) For each FK for which the table is the parent table, search
+ ** the child table for rows that correspond to the deleted row
+ ** in the parent table. For each found increment the counter.
**
- ** 1) The named parent key columns do not exist, or
+ ** UPDATE operations:
**
- ** 2) The named parent key columns do exist, but are not subject to a
- ** UNIQUE or PRIMARY KEY constraint, or
+ ** An UPDATE command requires that all 4 steps above are taken, but only
+ ** for FK constraints for which the affected columns are actually
+ ** modified (values must be compared at runtime).
**
- ** 3) No parent key columns were provided explicitly as part of the
- ** foreign key definition, and the parent table does not have a
- ** PRIMARY KEY, or
+ ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
+ ** This simplifies the implementation a bit.
**
- ** 4) No parent key columns were provided explicitly as part of the
- ** foreign key definition, and the PRIMARY KEY of the parent table
- ** consists of a different number of columns to the child key in
- ** the child table.
+ ** For the purposes of immediate FK constraints, the OR REPLACE conflict
+ ** resolution is considered to delete rows before the new row is inserted.
+ ** If a delete caused by OR REPLACE violates an FK constraint, an exception
+ ** is thrown, even if the FK constraint would be satisfied after the new
+ ** row is inserted.
**
- ** then non-zero is returned, and a "foreign key mismatch" error loaded
- ** into pParse. If an OOM error occurs, non-zero is returned and the
- ** pParse.db.mallocFailed flag is set.
- */
- static int locateFkeyIndex(
- Parse pParse, /* Parse context to store any error in */
- Table pParent, /* Parent table of FK constraint pFKey */
- FKey pFKey, /* Foreign key to find index for */
- out Index ppIdx, /* OUT: Unique index on parent table */
- out int[] paiCol /* OUT: Map of index columns in pFKey */
- )
- {
- Index pIdx = null; /* Value to return via *ppIdx */
- ppIdx = null;
- int[] aiCol = null; /* Value to return via *paiCol */
- paiCol = null;
-
- int nCol = pFKey.nCol; /* Number of columns in parent key */
- string zKey = pFKey.aCol[0].zCol; /* Name of left-most parent key column */
-
- /* The caller is responsible for zeroing output parameters. */
- //assert( ppIdx && *ppIdx==0 );
- //assert( !paiCol || *paiCol==0 );
- Debug.Assert( pParse != null );
-
- /* If this is a non-composite (single column) foreign key, check if it
- ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
- ** and *paiCol set to zero and return early.
- **
- ** Otherwise, for a composite foreign key (more than one column), allocate
- ** space for the aiCol array (returned via output parameter *paiCol).
- ** Non-composite foreign keys do not require the aiCol array.
- */
- if ( nCol == 1 )
- {
- /* The FK maps to the IPK if any of the following are true:
- **
- ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
- ** mapped to the primary key of table pParent, or
- ** 2) The FK is explicitly mapped to a column declared as INTEGER
- ** PRIMARY KEY.
- */
- if ( pParent.iPKey >= 0 )
- {
- if ( null == zKey )
- return 0;
- if ( pParent.aCol[pParent.iPKey].zName.Equals( zKey ,StringComparison.OrdinalIgnoreCase ) )
- return 0;
- }
- }
- else //if( paiCol ){
- {
- Debug.Assert( nCol > 1 );
- aiCol = new int[nCol];// (int*)sqlite3DbMallocRaw( pParse.db, nCol * sizeof( int ) );
- //if( !aiCol ) return 1;
- paiCol = aiCol;
- }
-
- for ( pIdx = pParent.pIndex; pIdx != null; pIdx = pIdx.pNext )
- {
- if ( pIdx.nColumn == nCol && pIdx.onError != OE_None )
- {
- /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
- ** of columns. If each indexed column corresponds to a foreign key
- ** column of pFKey, then this index is a winner. */
-
- if ( zKey == null )
- {
- /* If zKey is NULL, then this foreign key is implicitly mapped to
- ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
- ** identified by the test (Index.autoIndex==2). */
- if ( pIdx.autoIndex == 2 )
- {
- if ( aiCol != null )
- {
- int i;
- for ( i = 0; i < nCol; i++ )
- aiCol[i] = pFKey.aCol[i].iFrom;
- }
- break;
- }
- }
- else
- {
- /* If zKey is non-NULL, then this foreign key was declared to
- ** map to an explicit list of columns in table pParent. Check if this
- ** index matches those columns. Also, check that the index uses
- ** the default collation sequences for each column. */
- int i, j;
- for ( i = 0; i < nCol; i++ )
- {
- int iCol = pIdx.aiColumn[i]; /* Index of column in parent tbl */
- string zDfltColl; /* Def. collation for column */
- string zIdxCol; /* Name of indexed column */
-
- /* If the index uses a collation sequence that is different from
- ** the default collation sequence for the column, this index is
- ** unusable. Bail out early in this case. */
- zDfltColl = pParent.aCol[iCol].zColl;
- if ( String.IsNullOrEmpty( zDfltColl ) )
- {
- zDfltColl = "BINARY";
- }
- if ( !pIdx.azColl[i].Equals( zDfltColl ,StringComparison.OrdinalIgnoreCase ) )
- break;
-
- zIdxCol = pParent.aCol[iCol].zName;
- for ( j = 0; j < nCol; j++ )
- {
- if ( pFKey.aCol[j].zCol.Equals( zIdxCol ,StringComparison.OrdinalIgnoreCase ) )
- {
- if ( aiCol != null )
- aiCol[i] = pFKey.aCol[j].iFrom;
- break;
- }
- }
- if ( j == nCol )
- break;
- }
- if ( i == nCol )
- break; /* pIdx is usable */
- }
- }
- }
-
- if ( null == pIdx )
- {
- if ( 0 == pParse.disableTriggers )
- {
- sqlite3ErrorMsg( pParse, "foreign key mismatch" );
- }
- sqlite3DbFree( pParse.db, ref aiCol );
- return 1;
- }
-
- ppIdx = pIdx;
- return 0;
- }
-
- /*
- ** This function is called when a row is inserted into or deleted from the
- ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
- ** on the child table of pFKey, this function is invoked twice for each row
- ** affected - once to "delete" the old row, and then again to "insert" the
- ** new row.
+ ** Immediate constraints are usually handled similarly. The only difference
+ ** is that the counter used is stored as part of each individual statement
+ ** object (struct Vdbe). If, after the statement has run, its immediate
+ ** constraint counter is greater than zero, it returns SQLITE_CONSTRAINT
+ ** and the statement transaction is rolled back. An exception is an INSERT
+ ** statement that inserts a single row only (no triggers). In this case,
+ ** instead of using a counter, an exception is thrown immediately if the
+ ** INSERT violates a foreign key constraint. This is necessary as such
+ ** an INSERT does not open a statement transaction.
**
- ** Each time it is called, this function generates VDBE code to locate the
- ** row in the parent table that corresponds to the row being inserted into
- ** or deleted from the child table. If the parent row can be found, no
- ** special action is taken. Otherwise, if the parent row can *not* be
- ** found in the parent table:
+ ** TODO: How should dropping a table be handled? How should renaming a
+ ** table be handled?
**
- ** Operation | FK type | Action taken
- ** --------------------------------------------------------------------------
- ** INSERT immediate Increment the "immediate constraint counter".
**
- ** DELETE immediate Decrement the "immediate constraint counter".
+ ** Query API Notes
+ ** ---------------
**
- ** INSERT deferred Increment the "deferred constraint counter".
+ ** Before coding an UPDATE or DELETE row operation, the code-generator
+ ** for those two operations needs to know whether or not the operation
+ ** requires any FK processing and, if so, which columns of the original
+ ** row are required by the FK processing VDBE code (i.e. if FKs were
+ ** implemented using triggers, which of the old.* columns would be
+ ** accessed). No information is required by the code-generator before
+ ** coding an INSERT operation. The functions used by the UPDATE/DELETE
+ ** generation code to query for this information are:
**
- ** DELETE deferred Decrement the "deferred constraint counter".
+ ** sqlite3FkRequired() - Test to see if FK processing is required.
+ ** sqlite3FkOldmask() - Query for the set of required old.* columns.
**
- ** These operations are identified in the comment at the top of this file
- ** (fkey.c) as "I.1" and "D.1".
+ **
+ ** Externally accessible module functions
+ ** --------------------------------------
+ **
+ ** sqlite3FkCheck() - Check for foreign key violations.
+ ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
+ ** sqlite3FkDelete() - Delete an FKey structure.
*/
- static void fkLookupParent(
- Parse pParse, /* Parse context */
- int iDb, /* Index of database housing pTab */
- Table pTab, /* Parent table of FK pFKey */
- Index pIdx, /* Unique index on parent key columns in pTab */
- FKey pFKey, /* Foreign key constraint */
- int[] aiCol, /* Map from parent key columns to child table columns */
- int regData, /* Address of array containing child table row */
- int nIncr, /* Increment constraint counter by this */
- int isIgnore /* If true, pretend pTab contains all NULL values */
- )
- {
- int i; /* Iterator variable */
- Vdbe v = sqlite3GetVdbe( pParse ); /* Vdbe to add code to */
- int iCur = pParse.nTab - 1; /* Cursor number to use */
- int iOk = sqlite3VdbeMakeLabel( v ); /* jump here if parent key found */
-
- /* If nIncr is less than zero, then check at runtime if there are any
- ** outstanding constraints to resolve. If there are not, there is no need
- ** to check if deleting this row resolves any outstanding violations.
- **
- ** Check if any of the key columns in the child table row are NULL. If
- ** any are, then the constraint is considered satisfied. No need to
- ** search for a matching row in the parent table. */
- if ( nIncr < 0 )
- {
- sqlite3VdbeAddOp2( v, OP_FkIfZero, pFKey.isDeferred, iOk );
- }
- for ( i = 0; i < pFKey.nCol; i++ )
- {
- int iReg = aiCol[i] + regData + 1;
- sqlite3VdbeAddOp2( v, OP_IsNull, iReg, iOk );
- }
- if ( isIgnore == 0 )
- {
- if ( pIdx == null )
- {
- /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
- ** column of the parent table (table pTab). */
- int iMustBeInt; /* Address of MustBeInt instruction */
- int regTemp = sqlite3GetTempReg( pParse );
-
- /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
- ** apply the affinity of the parent key). If this fails, then there
- ** is no matching parent key. Before using MustBeInt, make a copy of
- ** the value. Otherwise, the value inserted into the child key column
- ** will have INTEGER affinity applied to it, which may not be correct. */
- sqlite3VdbeAddOp2( v, OP_SCopy, aiCol[0] + 1 + regData, regTemp );
- iMustBeInt = sqlite3VdbeAddOp2( v, OP_MustBeInt, regTemp, 0 );
-
- /* If the parent table is the same as the child table, and we are about
- ** to increment the constraint-counter (i.e. this is an INSERT operation),
- ** then check if the row being inserted matches itself. If so, do not
- ** increment the constraint-counter. */
- if ( pTab == pFKey.pFrom && nIncr == 1 )
- {
- sqlite3VdbeAddOp3( v, OP_Eq, regData, iOk, regTemp );
- }
-
- sqlite3OpenTable( pParse, iCur, iDb, pTab, OP_OpenRead );
- sqlite3VdbeAddOp3( v, OP_NotExists, iCur, 0, regTemp );
- sqlite3VdbeAddOp2( v, OP_Goto, 0, iOk );
- sqlite3VdbeJumpHere( v, sqlite3VdbeCurrentAddr( v ) - 2 );
- sqlite3VdbeJumpHere( v, iMustBeInt );
- sqlite3ReleaseTempReg( pParse, regTemp );
- }
- else
- {
- int nCol = pFKey.nCol;
- int regTemp = sqlite3GetTempRange( pParse, nCol );
- int regRec = sqlite3GetTempReg( pParse );
- KeyInfo pKey = sqlite3IndexKeyinfo( pParse, pIdx );
-
- sqlite3VdbeAddOp3( v, OP_OpenRead, iCur, pIdx.tnum, iDb );
- sqlite3VdbeChangeP4( v, -1, pKey, P4_KEYINFO_HANDOFF );
- for ( i = 0; i < nCol; i++ )
- {
- sqlite3VdbeAddOp2( v, OP_Copy, aiCol[i] + 1 + regData, regTemp + i );
- }
-
- /* If the parent table is the same as the child table, and we are about
- ** to increment the constraint-counter (i.e. this is an INSERT operation),
- ** then check if the row being inserted matches itself. If so, do not
- ** increment the constraint-counter.
- **
- ** If any of the parent-key values are NULL, then the row cannot match
- ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
- ** of the parent-key values are NULL (at this point it is known that
- ** none of the child key values are).
- */
- if ( pTab == pFKey.pFrom && nIncr == 1 )
- {
- int iJump = sqlite3VdbeCurrentAddr( v ) + nCol + 1;
- for ( i = 0; i < nCol; i++ )
- {
- int iChild = aiCol[i] + 1 + regData;
- int iParent = pIdx.aiColumn[i] + 1 + regData;
- Debug.Assert( aiCol[i] != pTab.iPKey );
- if ( pIdx.aiColumn[i] == pTab.iPKey )
+ /*
+ ** VDBE Calling Convention
+ ** -----------------------
+ **
+ ** Example:
+ **
+ ** For the following INSERT statement:
+ **
+ ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
+ ** INSERT INTO t1 VALUES(1, 2, 3.1);
+ **
+ ** Register (x): 2 (type integer)
+ ** Register (x+1): 1 (type integer)
+ ** Register (x+2): NULL (type NULL)
+ ** Register (x+3): 3.1 (type real)
+ */
+
+ /*
+ ** A foreign key constraint requires that the key columns in the parent
+ ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
+ ** Given that pParent is the parent table for foreign key constraint pFKey,
+ ** search the schema a unique index on the parent key columns.
+ **
+ ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
+ ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
+ ** is set to point to the unique index.
+ **
+ ** If the parent key consists of a single column (the foreign key constraint
+ ** is not a composite foreign key), refput variable *paiCol is set to NULL.
+ ** Otherwise, it is set to point to an allocated array of size N, where
+ ** N is the number of columns in the parent key. The first element of the
+ ** array is the index of the child table column that is mapped by the FK
+ ** constraint to the parent table column stored in the left-most column
+ ** of index *ppIdx. The second element of the array is the index of the
+ ** child table column that corresponds to the second left-most column of
+ ** *ppIdx, and so on.
+ **
+ ** If the required index cannot be found, either because:
+ **
+ ** 1) The named parent key columns do not exist, or
+ **
+ ** 2) The named parent key columns do exist, but are not subject to a
+ ** UNIQUE or PRIMARY KEY constraint, or
+ **
+ ** 3) No parent key columns were provided explicitly as part of the
+ ** foreign key definition, and the parent table does not have a
+ ** PRIMARY KEY, or
+ **
+ ** 4) No parent key columns were provided explicitly as part of the
+ ** foreign key definition, and the PRIMARY KEY of the parent table
+ ** consists of a different number of columns to the child key in
+ ** the child table.
+ **
+ ** then non-zero is returned, and a "foreign key mismatch" error loaded
+ ** into pParse. If an OOM error occurs, non-zero is returned and the
+ ** pParse.db.mallocFailed flag is set.
+ */
+ static int locateFkeyIndex(
+ Parse pParse, /* Parse context to store any error in */
+ Table pParent, /* Parent table of FK constraint pFKey */
+ FKey pFKey, /* Foreign key to find index for */
+ out Index ppIdx, /* OUT: Unique index on parent table */
+ out int[] paiCol /* OUT: Map of index columns in pFKey */
+ ) {
+ Index pIdx = null; /* Value to return via *ppIdx */
+ ppIdx = null;
+ int[] aiCol = null; /* Value to return via *paiCol */
+ paiCol = null;
+
+ int nCol = pFKey.nCol; /* Number of columns in parent key */
+ string zKey = pFKey.aCol[0].zCol; /* Name of left-most parent key column */
+
+ /* The caller is responsible for zeroing output parameters. */
+ //assert( ppIdx && *ppIdx==0 );
+ //assert( !paiCol || *paiCol==0 );
+ Debug.Assert(pParse != null);
+
+ /* If this is a non-composite (single column) foreign key, check if it
+ ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
+ ** and *paiCol set to zero and return early.
+ **
+ ** Otherwise, for a composite foreign key (more than one column), allocate
+ ** space for the aiCol array (returned via output parameter *paiCol).
+ ** Non-composite foreign keys do not require the aiCol array.
+ */
+ if (nCol == 1) {
+ /* The FK maps to the IPK if any of the following are true:
+ **
+ ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
+ ** mapped to the primary key of table pParent, or
+ ** 2) The FK is explicitly mapped to a column declared as INTEGER
+ ** PRIMARY KEY.
+ */
+ if (pParent.iPKey >= 0) {
+ if (null == zKey)
+ return 0;
+ if (pParent.aCol[pParent.iPKey].zName.Equals(zKey, StringComparison.OrdinalIgnoreCase))
+ return 0;
+ }
+ } else //if( paiCol ){
{
- /* The parent key is a composite key that includes the IPK column */
- iParent = regData;
- }
- sqlite3VdbeAddOp3( v, OP_Ne, iChild, iJump, iParent );
- sqlite3VdbeChangeP5( v, SQLITE_JUMPIFNULL );
+ Debug.Assert(nCol > 1);
+ aiCol = new int[nCol];// (int*)sqlite3DbMallocRaw( pParse.db, nCol * sizeof( int ) );
+ //if( !aiCol ) return 1;
+ paiCol = aiCol;
}
- sqlite3VdbeAddOp2( v, OP_Goto, 0, iOk );
- }
- sqlite3VdbeAddOp3( v, OP_MakeRecord, regTemp, nCol, regRec );
- sqlite3VdbeChangeP4( v, -1, sqlite3IndexAffinityStr( v, pIdx ), P4_TRANSIENT );
- sqlite3VdbeAddOp4Int( v, OP_Found, iCur, iOk, regRec, 0 );
+ for (pIdx = pParent.pIndex; pIdx != null; pIdx = pIdx.pNext) {
+ if (pIdx.nColumn == nCol && pIdx.onError != OE_None) {
+ /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
+ ** of columns. If each indexed column corresponds to a foreign key
+ ** column of pFKey, then this index is a winner. */
+
+ if (zKey == null) {
+ /* If zKey is NULL, then this foreign key is implicitly mapped to
+ ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
+ ** identified by the test (Index.autoIndex==2). */
+ if (pIdx.autoIndex == 2) {
+ if (aiCol != null) {
+ int i;
+ for (i = 0; i < nCol; i++)
+ aiCol[i] = pFKey.aCol[i].iFrom;
+ }
+ break;
+ }
+ } else {
+ /* If zKey is non-NULL, then this foreign key was declared to
+ ** map to an explicit list of columns in table pParent. Check if this
+ ** index matches those columns. Also, check that the index uses
+ ** the default collation sequences for each column. */
+ int i, j;
+ for (i = 0; i < nCol; i++) {
+ int iCol = pIdx.aiColumn[i]; /* Index of column in parent tbl */
+ string zDfltColl; /* Def. collation for column */
+ string zIdxCol; /* Name of indexed column */
+
+ /* If the index uses a collation sequence that is different from
+ ** the default collation sequence for the column, this index is
+ ** unusable. Bail out early in this case. */
+ zDfltColl = pParent.aCol[iCol].zColl;
+ if (String.IsNullOrEmpty(zDfltColl)) {
+ zDfltColl = "BINARY";
+ }
+ if (!pIdx.azColl[i].Equals(zDfltColl, StringComparison.OrdinalIgnoreCase))
+ break;
+
+ zIdxCol = pParent.aCol[iCol].zName;
+ for (j = 0; j < nCol; j++) {
+ if (pFKey.aCol[j].zCol.Equals(zIdxCol, StringComparison.OrdinalIgnoreCase)) {
+ if (aiCol != null)
+ aiCol[i] = pFKey.aCol[j].iFrom;
+ break;
+ }
+ }
+ if (j == nCol)
+ break;
+ }
+ if (i == nCol)
+ break; /* pIdx is usable */
+ }
+ }
+ }
- sqlite3ReleaseTempReg( pParse, regRec );
- sqlite3ReleaseTempRange( pParse, regTemp, nCol );
- }
- }
+ if (null == pIdx) {
+ if (0 == pParse.disableTriggers) {
+ sqlite3ErrorMsg(pParse, "foreign key mismatch");
+ }
+ sqlite3DbFree(pParse.db, ref aiCol);
+ return 1;
+ }
- if ( 0 == pFKey.isDeferred && null == pParse.pToplevel && 0 == pParse.isMultiWrite )
- {
- /* Special case: If this is an INSERT statement that will insert exactly
- ** one row into the table, raise a constraint immediately instead of
- ** incrementing a counter. This is necessary as the VM code is being
- ** generated for will not open a statement transaction. */
- Debug.Assert( nIncr == 1 );
- sqlite3HaltConstraint(
- pParse, OE_Abort, "foreign key constraint failed", P4_STATIC
- );
- }
- else
- {
- if ( nIncr > 0 && pFKey.isDeferred == 0 )
- {
- sqlite3ParseToplevel( pParse ).mayAbort = 1;
+ ppIdx = pIdx;
+ return 0;
}
- sqlite3VdbeAddOp2( v, OP_FkCounter, pFKey.isDeferred, nIncr );
- }
- sqlite3VdbeResolveLabel( v, iOk );
- sqlite3VdbeAddOp1( v, OP_Close, iCur );
- }
+ /*
+ ** This function is called when a row is inserted into or deleted from the
+ ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
+ ** on the child table of pFKey, this function is invoked twice for each row
+ ** affected - once to "delete" the old row, and then again to "insert" the
+ ** new row.
+ **
+ ** Each time it is called, this function generates VDBE code to locate the
+ ** row in the parent table that corresponds to the row being inserted into
+ ** or deleted from the child table. If the parent row can be found, no
+ ** special action is taken. Otherwise, if the parent row can *not* be
+ ** found in the parent table:
+ **
+ ** Operation | FK type | Action taken
+ ** --------------------------------------------------------------------------
+ ** INSERT immediate Increment the "immediate constraint counter".
+ **
+ ** DELETE immediate Decrement the "immediate constraint counter".
+ **
+ ** INSERT deferred Increment the "deferred constraint counter".
+ **
+ ** DELETE deferred Decrement the "deferred constraint counter".
+ **
+ ** These operations are identified in the comment at the top of this file
+ ** (fkey.c) as "I.1" and "D.1".
+ */
+ static void fkLookupParent(
+ Parse pParse, /* Parse context */
+ int iDb, /* Index of database housing pTab */
+ Table pTab, /* Parent table of FK pFKey */
+ Index pIdx, /* Unique index on parent key columns in pTab */
+ FKey pFKey, /* Foreign key constraint */
+ int[] aiCol, /* Map from parent key columns to child table columns */
+ int regData, /* Address of array containing child table row */
+ int nIncr, /* Increment constraint counter by this */
+ int isIgnore /* If true, pretend pTab contains all NULL values */
+ ) {
+ int i; /* Iterator variable */
+ Vdbe v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
+ int iCur = pParse.nTab - 1; /* Cursor number to use */
+ int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
+
+ /* If nIncr is less than zero, then check at runtime if there are any
+ ** outstanding constraints to resolve. If there are not, there is no need
+ ** to check if deleting this row resolves any outstanding violations.
+ **
+ ** Check if any of the key columns in the child table row are NULL. If
+ ** any are, then the constraint is considered satisfied. No need to
+ ** search for a matching row in the parent table. */
+ if (nIncr < 0) {
+ sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey.isDeferred, iOk);
+ }
+ for (i = 0; i < pFKey.nCol; i++) {
+ int iReg = aiCol[i] + regData + 1;
+ sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk);
+ }
- /*
- ** This function is called to generate code executed when a row is deleted
- ** from the parent table of foreign key constraint pFKey and, if pFKey is
- ** deferred, when a row is inserted into the same table. When generating
- ** code for an SQL UPDATE operation, this function may be called twice -
- ** once to "delete" the old row and once to "insert" the new row.
- **
- ** The code generated by this function scans through the rows in the child
- ** table that correspond to the parent table row being deleted or inserted.
- ** For each child row found, one of the following actions is taken:
- **
- ** Operation | FK type | Action taken
- ** --------------------------------------------------------------------------
- ** DELETE immediate Increment the "immediate constraint counter".
- ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
- ** throw a "foreign key constraint failed" exception.
- **
- ** INSERT immediate Decrement the "immediate constraint counter".
- **
- ** DELETE deferred Increment the "deferred constraint counter".
- ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
- ** throw a "foreign key constraint failed" exception.
- **
- ** INSERT deferred Decrement the "deferred constraint counter".
- **
- ** These operations are identified in the comment at the top of this file
- ** (fkey.c) as "I.2" and "D.2".
- */
- static void fkScanChildren(
- Parse pParse, /* Parse context */
- SrcList pSrc, /* SrcList containing the table to scan */
- Table pTab,
- Index pIdx, /* Foreign key index */
- FKey pFKey, /* Foreign key relationship */
- int[] aiCol, /* Map from pIdx cols to child table cols */
- int regData, /* Referenced table data starts here */
- int nIncr /* Amount to increment deferred counter by */
- )
- {
- sqlite3 db = pParse.db; /* Database handle */
- int i; /* Iterator variable */
- Expr pWhere = null; /* WHERE clause to scan with */
- NameContext sNameContext; /* Context used to resolve WHERE clause */
- WhereInfo pWInfo; /* Context used by sqlite3WhereXXX() */
- int iFkIfZero = 0; /* Address of OP_FkIfZero */
- Vdbe v = sqlite3GetVdbe( pParse );
-
- Debug.Assert( null == pIdx || pIdx.pTable == pTab );
-
- if ( nIncr < 0 )
- {
- iFkIfZero = sqlite3VdbeAddOp2( v, OP_FkIfZero, pFKey.isDeferred, 0 );
- }
+ if (isIgnore == 0) {
+ if (pIdx == null) {
+ /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
+ ** column of the parent table (table pTab). */
+ int iMustBeInt; /* Address of MustBeInt instruction */
+ int regTemp = sqlite3GetTempReg(pParse);
+
+ /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
+ ** apply the affinity of the parent key). If this fails, then there
+ ** is no matching parent key. Before using MustBeInt, make a copy of
+ ** the value. Otherwise, the value inserted into the child key column
+ ** will have INTEGER affinity applied to it, which may not be correct. */
+ sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0] + 1 + regData, regTemp);
+ iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
+
+ /* If the parent table is the same as the child table, and we are about
+ ** to increment the constraint-counter (i.e. this is an INSERT operation),
+ ** then check if the row being inserted matches itself. If so, do not
+ ** increment the constraint-counter. */
+ if (pTab == pFKey.pFrom && nIncr == 1) {
+ sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp);
+ }
+
+ sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
+ sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp);
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
+ sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v) - 2);
+ sqlite3VdbeJumpHere(v, iMustBeInt);
+ sqlite3ReleaseTempReg(pParse, regTemp);
+ } else {
+ int nCol = pFKey.nCol;
+ int regTemp = sqlite3GetTempRange(pParse, nCol);
+ int regRec = sqlite3GetTempReg(pParse);
+ KeyInfo pKey = sqlite3IndexKeyinfo(pParse, pIdx);
+
+ sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx.tnum, iDb);
+ sqlite3VdbeChangeP4(v, -1, pKey, P4_KEYINFO_HANDOFF);
+ for (i = 0; i < nCol; i++) {
+ sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i] + 1 + regData, regTemp + i);
+ }
+
+ /* If the parent table is the same as the child table, and we are about
+ ** to increment the constraint-counter (i.e. this is an INSERT operation),
+ ** then check if the row being inserted matches itself. If so, do not
+ ** increment the constraint-counter.
+ **
+ ** If any of the parent-key values are NULL, then the row cannot match
+ ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
+ ** of the parent-key values are NULL (at this point it is known that
+ ** none of the child key values are).
+ */
+ if (pTab == pFKey.pFrom && nIncr == 1) {
+ int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
+ for (i = 0; i < nCol; i++) {
+ int iChild = aiCol[i] + 1 + regData;
+ int iParent = pIdx.aiColumn[i] + 1 + regData;
+ Debug.Assert(aiCol[i] != pTab.iPKey);
+ if (pIdx.aiColumn[i] == pTab.iPKey) {
+ /* The parent key is a composite key that includes the IPK column */
+ iParent = regData;
+ }
+ sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent);
+ sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
+ }
+ sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
+ }
+
+ sqlite3VdbeAddOp3(v, OP_MakeRecord, regTemp, nCol, regRec);
+ sqlite3VdbeChangeP4(v, -1, sqlite3IndexAffinityStr(v, pIdx), P4_TRANSIENT);
+ sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0);
+
+ sqlite3ReleaseTempReg(pParse, regRec);
+ sqlite3ReleaseTempRange(pParse, regTemp, nCol);
+ }
+ }
- /* Create an Expr object representing an SQL expression like:
- **
- ** = AND